Connection class provides direct WebSocket communication with Chrome DevTools Protocol (CDP). It manages the underlying connection, event handlers, and CDP command execution.
Overview
The Connection class is the foundation for browser automation in Zendriver. It handles:- WebSocket communication with browser targets
- CDP command execution and response handling
- Event listener registration and management
- Target information and state management
Creating a connection
Connections are typically created automatically when you create tabs or browser instances. However, you can work with them directly:Properties
target_id
Returns the target ID of the current target.The unique identifier for the current target. Returns
None if no target is set.url
Returns the URL of the current target.The current URL of the target. Returns
None if no target is set.title
Returns the title of the current target.The page title of the target. Returns
None if no target is set.type_
Returns the type of the current target.The target type (e.g., “page”, “background_page”). Returns
None if no target is set.closed
Indicates whether the WebSocket connection is closed.True if the connection is closed, False otherwise.Methods
send()
Send a CDP command to the browser.The generator object created by a CDP method (e.g.,
cdp.page.navigate()).Internal flag to prevent infinite loops during handler registration.
add_handler()
Add an event handler for CDP events.The event type to listen for, or a CDP domain module to listen to all events in that domain.
The callback function to execute when the event occurs. Can be sync or async.
remove_handlers()
Remove event handlers.The event type to remove handlers for. If
None, removes all handlers.The specific handler to remove. If
None, removes all handlers for the event type.wait()
Wait until the event listener reports idle or for a specific duration.Number of seconds to wait. If provided, ensures waiting for exactly
t seconds. If None, waits until the connection is idle.update_target()
Update the target information from the browser.aopen()
Open the WebSocket connection. This is called automatically when needed.aclose()
Close the WebSocket connection.feed_cdp()
Send a CDP command without blocking. Useful duringcdp.fetch.RequestPaused events.
The generator object created by a CDP method.
Context manager support
Connection supports async context manager protocol:Advanced properties
The Connection class provides additional properties for advanced use cases:attached: Whether the target is attachedcan_access_opener: Whether the target can access its openeropener_id: The opener target IDopener_frame_id: The opener frame IDbrowser_context_id: The browser context IDsubtype: The target subtype
Related
- CDP Reference - Chrome DevTools Protocol usage
- Expect Methods - Wait for network events
- Intercept - Intercept and modify requests