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.

Implementation:SeleniumHQ Selenium DevTools Close

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

Overview

Concrete tool for closing a CDP session and WebSocket connection provided by the Selenium DevTools Java API.

Description

DevTools.disconnectSession() detaches from the current CDP target while keeping the WebSocket open for potential re-attachment. It performs three steps, each guarded by exception handlers to ensure cleanup proceeds even on failure:

  1. Disables the network domain via getDomains().network().disable() to cancel any pending interceptions
  2. Clears the internal cdpSession (SessionID) and windowHandle volatile fields
  3. Sends Target.detachFromTarget(sessionId) via the connection

DevTools.close() implements Closeable and performs full cleanup: calls disconnectSession() first, then delegates to Connection.close(), which closes the WebSocket (socket.close()), closes the HTTP client (client.close()), and sets the isClosed atomic flag to true.

clearListeners() provides a separate cleanup path: it calls getDomains().disableAll() to disable all enabled CDP domains, then calls connection.clearListeners() which clears the event callbacks map under a write lock.

All exception handling in disconnectSession() is non-propagating: exceptions are caught and logged at WARNING level rather than thrown, ensuring that cleanup completes even when the browser is in an unexpected or crashed state.

Usage

Call close() in a finally block or try-with-resources when done with CDP operations. Call disconnectSession() when re-targeting to a different tab. Note that createSession() can reopen a closed connection, so close() is not necessarily terminal.

Code Reference

Source Location

  • Repository: Selenium
  • File: java/src/org/openqa/selenium/devtools/DevTools.java (L62-92, L133-138)
  • File: java/src/org/openqa/selenium/devtools/Connection.java (L235-240)

Signature

// DevTools cleanup methods
public class DevTools implements Closeable {
    public void disconnectSession();
    @Override
    public void close();
    public void clearListeners();
}

// Connection cleanup
public class Connection implements Closeable {
    @Override
    public void close();       // closes WebSocket, HTTP client, sets isClosed
    boolean isClosed();        // checks AtomicBoolean flag
    void reopen();             // recreates HTTP client and WebSocket
    public void clearListeners(); // clears eventCallbacks under write lock
}

Import

import org.openqa.selenium.devtools.DevTools;

I/O Contract

Inputs

Name Type Required Description
(none) - - Called on an active DevTools instance

Outputs

Name Type Description
(void) void For disconnectSession(): CDP session detached, volatile fields cleared, WebSocket still open
(void) void For close(): session detached, WebSocket closed, HTTP client closed, isClosed set to true
(void) void For clearListeners(): all domains disabled, all event callbacks removed

Usage Examples

Full Cleanup with close()

DevTools devTools = driver.getDevTools();
try {
    devTools.createSession();
    devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
    // ... CDP operations
} finally {
    devTools.close(); // disconnects session, closes WebSocket and HTTP client
}
driver.quit();

Tab Switching with disconnectSession()

DevTools devTools = driver.getDevTools();
devTools.createSession();
// ... work on first tab ...

// Switch to new tab, disconnect from old target
devTools.disconnectSession();
driver.switchTo().newWindow(WindowType.TAB);

// Re-attach to new tab (WebSocket was kept open)
devTools.createSession(driver.getWindowHandle());
// ... work on second tab ...

devTools.close();
driver.quit();

Clearing Listeners Between Phases

DevTools devTools = driver.getDevTools();
devTools.createSession();

// Phase 1: monitor network
devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
devTools.addListener(Network.requestWillBeSent(), req -> { /* ... */ });
driver.get("https://example.com");

// Clean up phase 1 listeners and disabled domains
devTools.clearListeners();

// Phase 2: monitor console
devTools.send(Log.enable());
devTools.addListener(Log.entryAdded(), entry -> { /* ... */ });
driver.get("https://example.com/page2");

devTools.close();
driver.quit();

Related Pages

Implements Principle

Page Connections

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