Principle:SeleniumHQ Selenium CDP Session Cleanup
| Knowledge Sources | |
|---|---|
| Domains | Browser_Automation, DevTools, Resource_Management |
| Last Updated | 2026-02-11 00:00 GMT |
Overview
Procedure for properly detaching from a CDP session, clearing event listeners, and closing the WebSocket connection to prevent resource leaks.
Description
CDP session cleanup involves two primary operations on the DevTools class:
disconnectSession() detaches from the current target without closing the WebSocket. It first disables the network domain (to cancel any pending interceptions that could block the disconnect), then clears the internal SessionID and windowHandle, and finally sends Target.detachFromTarget() via the connection. Exceptions during any of these steps are caught and logged at WARNING level rather than propagated, to ensure cleanup completes even when the browser is in an unexpected state.
close() performs full cleanup by calling disconnectSession() first, then closing the underlying Connection. The Connection.close() method closes the WebSocket and the HTTP client, and marks the connection as closed. After close(), the DevTools instance is not directly reusable, though createSession() will attempt to reopen the connection if it detects it has been closed.
Additionally, clearListeners() explicitly removes all event listeners and disables all CDP domains via getDomains().disableAll(), while also clearing the listener map on the Connection.
Usage
Call disconnectSession() when switching between targets (e.g., tabs), and close() when done with all CDP operations. If using driver.quit(), CDP cleanup happens automatically. For long-running tests with multiple CDP phases, explicit cleanup between phases prevents resource accumulation.
Theoretical Basis
# Pseudocode: CDP Session Cleanup
disconnectSession():
1. If cdpSession is not null:
a. Try: domains.network().disable() (prevents pending interceptions from blocking)
b. Store sessionId reference, set cdpSession = null, windowHandle = null
c. Try: connection.sendAndWait(Target.detachFromTarget(sessionId))
d. All exceptions caught and logged at WARNING level
close():
1. Call disconnectSession()
2. Call connection.close():
a. socket.close() (close WebSocket)
b. client.close() (close HTTP client)
c. isClosed.set(true) (mark connection as closed)
clearListeners():
1. Call getDomains().disableAll() (disable all enabled CDP domains)
2. Call connection.clearListeners() (clear eventCallbacks map under write lock)