Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Principle:SeleniumHQ Selenium CDP Event Subscription

From Leeroopedia
Knowledge Sources
Domains Browser_Automation, DevTools, Event_Driven
Last Updated 2026-02-11 00:00 GMT

Overview

Asynchronous mechanism for registering callbacks that receive typed Chrome DevTools Protocol events as they occur in the browser.

Description

CDP events are asynchronous notifications from the browser about state changes (network requests, console messages, DOM mutations, etc.). Events are domain-scoped: the domain must be enabled first (e.g., Network.enable()) before its events fire. Selenium provides DevTools.addListener() to register typed Consumer<X> callbacks for specific Event<X> types. Events arrive on a daemon background thread pool (CDP Connection threads) managed by a cached thread executor and are dispatched to all registered listeners whose Event.getMethod() matches the incoming message's "method" field.

The Connection class maintains a map of Event<?> to List<BiConsumer<Long, ?>> protected by a ReadWriteLock. The read lock uses tryLock() to avoid deadlocks when an event handler waits for another event during processing. Each event also carries a sequence number (auto-incrementing across all events) that can be used to determine event ordering.

Usage

Use when you need to monitor browser behavior in real-time: capturing network requests/responses, logging console messages, detecting page errors, or waiting for specific browser state changes. Enable the relevant CDP domain first, then register listeners.

Theoretical Basis

# Pseudocode: CDP Event Subscription
1. Enable the domain: send(Network.enable())
2. Register listener: addListener(Network.requestWillBeSent(), handler)
   - Connection stores handler in eventCallbacks map under the Event key
   - Protected by ReadWriteLock (write lock for registration)
3. Browser generates event: { "method": "Network.requestWillBeSent", "params": {...} }
4. Connection.Listener.onText() receives WebSocket message
5. Message dispatched to background EXECUTOR thread
6. Connection.handle() acquires read lock (tryLock to avoid deadlock)
7. Iterates eventCallbacks entries, matches "method" field
8. For each matching Event: deserializes "params" using Event.getMapper()
9. Invokes all registered BiConsumer<Long, X> handlers with (sequence, data)
10. Read lock released

Related Pages

Implemented By

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment