When you open DevTools in an Electron app, the panel you click through is only the surface. Underneath, every interaction — reading a variable, stepping through code, capturing a console line, taking a screenshot, sampling performance — travels over the Chrome DevTools Protocol (CDP), a text-based JSON protocol spoken between a client and a Chromium target. Because Electron embeds Chromium, each render process, utility process, and window can be reached over that same protocol. Learning the protocol layer lets you do what the DevTools UI cannot: inspect many targets in one script, collect diagnostics programmatically from inside your own app, batch screenshots for smoke checks, and feed renderer failures into your existing logging pipeline. This guide covers how Electron exposes CDP targets, how you discover and connect to them, the domains that earn their keep in practice, how to attach the debugger from the main process without opening a port, where automation fits, and the security boundaries that keep this powerful interface from becoming a back door. It assumes you already know how to use DevTools day to day; the focus here is the protocol underneath it.

TL;DR

  • DevTools is a CDP client. The panel talks JSON over a WebSocket; the same commands are available to your own scripts and your own main process.
  • Two ways to reach a target. The port route (--remote-debugging-port) exposes an HTTP discovery endpoint plus per-target WebSockets; the in-app route uses webContents.debugger.attach and needs no open port at all.
  • Discover before you connect. Query /json/list, match the target by url or title, then open the WebSocket at its webSocketDebuggerUrl.
  • Enable a domain before its events arrive. Sending Runtime.enable or Console.enable subscribes you to that domain's events; commands and events are matched by an integer message id.
  • High-value domains: Runtime for evaluation, Console and Runtime for logs and exceptions, Page for navigation and screenshots, Performance for metrics, Network and DOM for inspection, Profiler for CPU samples.
  • Treat a CDP session like page-level code execution. It can read state and run arbitrary JavaScript, so the debugger must stay localhost-bound and behind an internal diagnostic switch in production.
  • Confirm the context is ready before evaluating. A target that navigates or restarts drops the session; re-enable domains and resubscribe after reconnecting.

Table of contents

  1. Why the protocol layer matters
  2. How Electron exposes CDP
  3. Discovering targets over the HTTP endpoints
  4. Connecting a WebSocket session
  5. The CDP domains worth knowing
  6. In-app diagnostics with webContents.debugger
  7. Automation: screenshots, smoke checks, and batch runs
  8. Security boundaries you must keep
  9. Common pitfalls
  10. Checklist

Why the protocol layer matters

A browser DevTools panel is built around a single assumption: a human is looking at one page at a time. Electron apps break that assumption regularly. You may have several windows, a background renderer, a preload context, and utility processes open at once. You may need to check whether a remote user's renderer is throwing exceptions after a release, capture a screenshot of a broken layout on a specific build, or compare startup metrics across three channels. Clicking through each window by hand does not scale, and it cannot be wired into an automated report.

CDP removes the panel from the loop. The protocol defines a small message model: a client sends a command with a method name and parameters, the target replies with a matching result or an error, and the target pushes events when something happens. Domains group related commands and events by responsibility — Runtime for JavaScript execution, Page for navigation and screenshots, Network for traffic, and so on. Once you speak that model, the same client can drive the DevTools UI, a standalone Node script, or a diagnostic module compiled into your main process.

One framing keeps the rest of this guide honest: CDP in Electron mostly reaches renderer and utility targets. The main process is a Node.js runtime, and its debugger is the standard Node inspector (--inspect), not a page-style CDP target. The port you open for CDP exposes Chromium targets; do not expect to evaluate main-process modules through a Runtime.evaluate against a renderer target.

How Electron exposes CDP

The most direct route is a command-line switch that starts Chromium's remote debugging server. You set it from the main process before the app creates its windows:

// main/index.js — development-only switch const { app } = require('electron'); if (!app.isPackaged) { // Bind to the loopback interface only; see the security section. app.commandLine.appendSwitch('remote-debugging-port', '9229'); } app.whenReady().then(() => { // BrowserWindow instances become CDP targets once their renderer loads. }); 

When that switch is present, Electron serves an HTTP endpoint on 127.0.0.1:9229. The root /json/version reports the browser and protocol version and the WebSocket URL for the browser-level target; /json/list lists every reachable page, worker, and background target with its id, title, URL, and webSocketDebuggerUrl.

The second route never opens a network port. Electron exposes a debugger object on each WebContents that speaks CDP directly between the main process and that renderer:

// main process const wc = BrowserWindow.fromId(targetWindowId).webContents; wc.debugger.attach('1.3'); wc.debugger.on('message', (_event, method, params) => { console.log('CDP event', method, params); }); await wc.debugger.sendCommand('Runtime.evaluate', { expression: 'location.href' }); wc.debugger.detach(); 

This in-app debugger is the right choice for diagnostics you ship inside the product: it is per-window, it lives in the trusted main process, and it does not depend on a port being free or a firewall permitting a connection. The port route is better for external tooling and batch automation, where a separate script discovers and drives many targets.

Discovering targets over the HTTP endpoints

Before any WebSocket command, you need to know which target to connect to. The HTTP endpoints are plain JSON over loopback:

GET http://127.0.0.1:9229/json/version GET http://127.0.0.1:9229/json/list 

A /json/list entry looks roughly like this:

{ "id": "8A3F2C1D4E5B6A78901234567890ABCD", "type": "page", "title": "Workspace — DevDesk", "url": "https://app.local/renderer/workspace", "webSocketDebuggerUrl": "ws://127.0.0.1:9229/devtools/page/8A3F2C1D4E5B6A78901234567890ABCD" } 

Match on a stable signal rather than array position. A multi-window app will return several page targets, plus any worker or background target, and their order is not guaranteed. Prefer a substring of url, a known title prefix, or a marker you inject into the page's document.title early in boot. If your app opens windows lazily, poll /json/list until the target you expect appears; a window that has not finished loading may not be listed yet.

Connecting a WebSocket session

A CDP client speaks one WebSocket per target. Each outbound message carries an integer id, a method, and params; responses echo that id with a result or an error; unsolicited messages are events with a method and params and no id. A minimal Node client using the ws package looks like this:

const WebSocket = require('ws'); const list = await fetch('http://127.0.0.1:9229/json/list').then((r) => r.json()); const target = list.find( (t) => t.type === 'page' && t.url.includes('/renderer/workspace') ); const ws = new WebSocket(target.webSocketDebuggerUrl); let nextId = 0; function send(method, params = {}) { return new Promise((resolve, reject) => { const msgId = ++nextId; const onMessage = (data) => { const msg = JSON.parse(data); if (msg.id !== msgId) return; ws.off('message', onMessage); msg.error ? reject(msg.error) : resolve(msg.result); }; ws.on('message', onMessage); ws.send(JSON.stringify({ id: msgId, method, params })); }); } ws.on('open', async () => { await send('Runtime.enable'); const evaluated = await send('Runtime.evaluate', { expression: '({ url: location.href, title: "document.title, nodes: document.querySelectorAll(\"*\").length })'," returnByValue: true, awaitPromise: true, }); console.log(evaluated.result.value); }); 

A few details decide whether this works in practice. returnByValue: true asks CDP to serialize the result back into JSON; without it you receive an objectId and must call Runtime.getProperties to walk the object. awaitPromise: true lets an evaluated expression return a promise that resolves before the result comes back. Events only arrive after you enable the relevant domain, so subscribe first, then act.

The CDP domains worth knowing

You do not need the whole protocol for most Electron diagnostics. A small core covers the common cases:

Domain What it is for Representative command or event
Runtime Evaluate expressions, read globals, catch uncaught exceptions Runtime.evaluate; Runtime.exceptionThrown
Console Capture renderer console.* calls Console.enable; consoleAPICalled
Page Navigate, capture screenshots, observe load lifecycle Page.navigate; Page.captureScreenshot; Page.loadEventFired
Performance Read JS heap, DOM, and timing metrics Performance.enable; Performance.getMetrics
Network Inspect requests, responses, and failures Network.enable; Network.requestWillBeSent; Network.responseReceived
DOM Inspect nodes and attributes without the panel DOM.getDocument; DOM.querySelector
Profiler Collect a CPU sampling profile Profiler.start; Profiler.stop; Profiler.getProfile
Log Browser-level entries that do not reach console Log.enable; Log.entryAdded

Reading metrics is a one-liner once Performance is enabled:

await send('Performance.enable'); const { metrics } = await send('Performance.getMetrics'); console.log(Object.fromEntries(metrics.map((m) => [m.name, m.value]))); 

The returned set includes JS heap size, DOM node count, event listeners, layout counters, and timing measures. It is enough to spot a renderer that has grown its heap between two builds, or to compare a window before and after a heavy interaction.

In-app diagnostics with webContents.debugger

The port route is external tooling. For diagnostics that live inside your shipped app, the main-process debugger attached to a specific WebContents is a better fit. It gives your trusted main process the same command surface over an internal object, with no listening socket.

// main process function attachDiagnostics(webContents) { const debugger_ = webContents.debugger; debugger_.attach('1.3'); debugger_.on('message', (_event, method, params) => { if (method === 'Runtime.consoleAPICalled') { const text = params.args .map((a) => a.value ?? a.description ?? a.type) .join(' '); console.log(`[renderer ${webContents.id}] ${params.type}: ${text}`); } else if (method === 'Runtime.exceptionThrown') { const desc = params.exceptionDetails.exception?.description; console.error(`[renderer ${webContents.id}] exception:`, desc); } }); return { async evaluate(expression) { const res = await debugger_.sendCommand('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true, }); return res.result?.value; }, async screenshot() { const shot = await debugger_.sendCommand('Page.captureScreenshot', { format: 'png' }); return Buffer.from(shot.data, 'base64'); }, detach() { if (debugger_.isAttached()) debugger_.detach(); }, }; } 

This pattern feeds renderer logs and exceptions straight into the same main-process logging channel you already maintain. A diagnostic panel in your own app can call evaluate to read a component's internal state, or screenshot to capture what the user sees when a layout breaks. Keep attachment behind an explicit internal switch; see the security section before wiring this to anything that talks to an outside session.

Automation: screenshots, smoke checks, and batch runs

Once a target is reachable over CDP, the same session supports light automation that does not need a full E2E framework. A boot smoke check can open the app, wait for Page.loadEventFired, evaluate a small invariant (for example, that the root view mounted and the error boundary is empty), capture a Page.captureScreenshot, and record the result. That screenshot doubles as evidence when a reported layout issue cannot be reproduced locally.

It is worth knowing how this relates to higher-level automation. Playwright and similar drivers speak CDP under the hood to Electron and Chromium targets; if your need is broad cross-window E2E, use the driver rather than hand-rolling a WebSocket client. Drop to the raw protocol when you need something the driver does not expose: a specific metric, a profile sample, an internal-state read from a shipped build, or a screenshot sequence that follows your app's own lifecycle.

Security boundaries you must keep

A CDP session has roughly the same power as sitting at the DevTools console: it can read page state, run arbitrary JavaScript in the renderer, and capture the screen. Treat it accordingly.

Boundary Safe default What to avoid
Network binding Keep debugging on 127.0.0.1 only Binding to 0.0.0.0 or exposing the port over a LAN/VPN without auth
Build target Open the port only in development Leaving --remote-debugging-port on in packaged production builds
In-app debugger Attach only behind an internal, opt-in diagnostic switch Attaching on boot and forwarding the session to an untrusted remote
Renderer trust Do not let untrusted renderer content request a debugger attach or raw CDP relay An IPC handler that lets the renderer hand the main process' debugger to an outside caller
Secrets Assume anything readable in the page context is visible to an attached debugger Sending tokens through renderer globals you later expose over a diagnostic session

There is no separate authentication layer on the loopback debugging port: any local process can connect to it. That is acceptable for a developer laptop where the user already controls the machine, but it means you should not run the port on a shared or kiosk machine, and you should never publish a production build that leaves it enabled. The in-app debugger is safer because it is gated by your own main-process logic, but the commands it issues are still renderer-level, so do not relay those sessions to external callers.

Common pitfalls

  • The port moved. If 9229 is already taken, Electron picks the next available port. Read the actual port from /json/version or your app's launch output instead of hard-coding the assumption.
  • You matched the wrong target. Multiple windows and background pages share the port. Match by URL or title marker, never by the first entry in /json/list.
  • Evaluating before the context exists. An early Runtime.evaluate can run before your bundle has mounted, returning undefined or throwing. Wait for a load event, or poll a marker your page sets on boot.
  • Isolated worlds. Preload scripts and injected content may run in a different execution world than the page's main context. If a global you expect is missing, check the contextId the expression runs in.
  • Holding onto non-serializable results. Objects passed back without returnByValue are objectId references; dereference them with Runtime.getProperties before the target navigates or the reference expires.
  • Dropped sessions on navigation or restart. A renderer reload, crash, or app restart closes the WebSocket. On reconnect you must re-enable domains and resubscribe to events; state in the old session does not carry over.
  • Confusing Node debugging with CDP. To debug the main process, launch Node with --inspect and use the Node inspector; CDP page targets do not expose main-process modules.

Checklist

  • Confirm whether you need an external script (port route) or an in-app diagnostic (webContents debugger).
  • Open the debug port only in development, bound to the loopback interface.
  • Discover targets from /json/list and match on URL or title marker, not position.
  • Enable each domain before relying on its events; match responses by message id.
  • Use returnByValue and awaitPromise on Runtime.evaluate; dereference object ids explicitly when needed.
  • Subscribe to Runtime.exceptionThrown and consoleAPICalled to route renderer problems into your existing logs.
  • Capture screenshots and Performance.getMetrics as evidence, not as a substitute for reproducing the issue.
  • Gate any in-app debugger behind an internal switch and never relay its session to an untrusted caller.
  • Reconnect and re-enable domains after a navigation or renderer restart; do not assume the old session survives.
  • Reach for a dedicated E2E driver for broad cross-window flows; drop to raw CDP only for the metrics, profiles, or internal reads the driver does not expose.