pub struct CdpClient { /* private fields */ }Expand description
A single WebSocket session to one Chrome debugging target.
Cloning is not supported; share a client across tasks with Arc<CdpClient>
(see Cluster for an example). Every command sent
concurrently gets its own response future, matched by CDP message id.
Implementations§
Source§impl CdpClient
impl CdpClient
Sourcepub async fn connect(ws_url: &str) -> Result<Self>
pub async fn connect(ws_url: &str) -> Result<Self>
Open a CDP WebSocket session at ws_url (a target’s webSocketDebuggerUrl).
Spawns background tasks that pump outgoing commands and demultiplex incoming replies/events for the lifetime of the returned client.
Sourcepub fn set_command_timeout(&self, timeout: Duration)
pub fn set_command_timeout(&self, timeout: Duration)
Set the per-command timeout applied to every CDP command this client sends. Passing a zero duration disables the timeout (commands wait indefinitely).
Sourcepub fn command_timeout(&self) -> Duration
pub fn command_timeout(&self) -> Duration
The current per-command timeout.
Sourcepub async fn call<P: Serialize, R: DeserializeOwned>(
&self,
method: &str,
params: P,
) -> Result<R>
pub async fn call<P: Serialize, R: DeserializeOwned>( &self, method: &str, params: P, ) -> Result<R>
Send any CDP command and deserialize its result into R.
The typed wrappers on this client cover only a small, curated slice of the
DevTools Protocol; this is the escape hatch for everything else, including
domains this crate has no wrappers for at all (Target, Storage,
Debugger, …). params must serialize to a JSON object, since that is
what CDP expects; use json!({}) for commands that take no parameters.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct CreateTarget {
target_id: String,
}
let created: CreateTarget = client
.call("Target.createTarget", json!({ "url": "about:blank" }))
.await?;Sourcepub async fn call_raw(&self, method: &str, params: Value) -> Result<Value>
pub async fn call_raw(&self, method: &str, params: Value) -> Result<Value>
Send any CDP command and return its raw result object unparsed.
Prefer call when you have a type to deserialize into. This is
the lower-level form, useful for exploring a response’s shape or for commands
whose result you only want to index into. Commands that return no result
yield Value::Null.
Sourcepub fn subscribe_events(&self) -> Receiver<(String, Value)>
pub fn subscribe_events(&self) -> Receiver<(String, Value)>
Subscribe to raw CDP events as (method, params) pairs.
Only events for domains enabled via enable_domain
are emitted. Lagging receivers silently drop the oldest events rather than
blocking the connection.
These are the events of the target this client connected to. Events raised
by an attached session (attach_to_target) do not
appear here, because a (method, params) pair cannot say which target it
came from; use subscribe_session_events
to see those.
Sourcepub fn subscribe_session_events(&self) -> Receiver<SessionEvent>
pub fn subscribe_session_events(&self) -> Receiver<SessionEvent>
Subscribe to every CDP event on this connection, each tagged with the
session it came from (SessionEvent::session_id is None for the target
this client connected to directly).
Sourcepub async fn wait_for_event(
&self,
method: &str,
timeout_ms: u64,
) -> Result<Value>
pub async fn wait_for_event( &self, method: &str, timeout_ms: u64, ) -> Result<Value>
Wait for the next event named method, up to timeout_ms milliseconds.
Sourcepub async fn enable_domain(&self, domain: &str) -> Result<()>
pub async fn enable_domain(&self, domain: &str) -> Result<()>
Enable a CDP domain (e.g. "Page", "Runtime", "Network"), required before
that domain’s events start flowing or some of its commands work.
Source§impl CdpClient
impl CdpClient
Sourcepub async fn get_version(host: &str, port: u16) -> Result<BrowserVersion>
pub async fn get_version(host: &str, port: u16) -> Result<BrowserVersion>
GET /json/version on Chrome’s debugging HTTP endpoint.
Sourcepub async fn list_targets(host: &str, port: u16) -> Result<Vec<Target>>
pub async fn list_targets(host: &str, port: u16) -> Result<Vec<Target>>
GET /json/list: enumerate debuggable targets (tabs, workers, …).
Sourcepub async fn connect_to_page(host: &str, port: u16) -> Result<Self>
pub async fn connect_to_page(host: &str, port: u16) -> Result<Self>
Connect to the first target of type "page" reported by list_targets.
Returns CdpError::NoTarget if none exists.
Source§impl CdpClient
impl CdpClient
Sourcepub async fn get_document(&self) -> Result<DocumentNode>
pub async fn get_document(&self) -> Result<DocumentNode>
Fetch the document’s root node. Requires the "DOM" domain to be enabled.
Sourcepub async fn query_selector(
&self,
node_id: i64,
selector: &str,
) -> Result<Option<i64>>
pub async fn query_selector( &self, node_id: i64, selector: &str, ) -> Result<Option<i64>>
Returns the matched nodeId, or None when nothing matches.
CDP reports a missing match as nodeId 0; this surfaces that as None
rather than a node id that looks valid.
Sourcepub async fn get_outer_html(&self, node_id: i64) -> Result<String>
pub async fn get_outer_html(&self, node_id: i64) -> Result<String>
Serialize a node’s outer HTML.
Source§impl CdpClient
impl CdpClient
Set a cookie. url or domain is required by CDP to resolve which
site the cookie belongs to.
Delete cookies matching name (and optionally scoped to url).
Sourcepub async fn set_extra_headers(
&self,
headers: &HashMap<String, String>,
) -> Result<()>
pub async fn set_extra_headers( &self, headers: &HashMap<String, String>, ) -> Result<()>
Send headers with every subsequent request from this target.
Sourcepub async fn block_urls(&self, patterns: &[&str]) -> Result<()>
pub async fn block_urls(&self, patterns: &[&str]) -> Result<()>
Block requests whose URL matches any of patterns (CDP wildcard syntax, e.g.
"*.example.com/*").
Sourcepub async fn get_response_body(&self, request_id: &str) -> Result<String>
pub async fn get_response_body(&self, request_id: &str) -> Result<String>
Fetch a response body by request id, decoding it if Chrome returned it base64-encoded.
Sourcepub async fn intercept_requests(&self, url_patterns: &[&str]) -> Result<()>
pub async fn intercept_requests(&self, url_patterns: &[&str]) -> Result<()>
Enable request interception for URLs matching url_patterns. Matching requests
pause and must be resolved with continue_request or
fulfill_request, delivered as Fetch.requestPaused
events (see subscribe_events).
Sourcepub async fn continue_request(&self, request_id: &str) -> Result<()>
pub async fn continue_request(&self, request_id: &str) -> Result<()>
Let a paused request proceed unmodified.
Sourcepub async fn fulfill_request(
&self,
request_id: &str,
status: u16,
body: &str,
content_type: &str,
) -> Result<()>
pub async fn fulfill_request( &self, request_id: &str, status: u16, body: &str, content_type: &str, ) -> Result<()>
Respond to a paused request with a synthetic response instead of letting it reach the network.
List cookies visible to the current page.
Source§impl CdpClient
impl CdpClient
Sourcepub async fn set_content(&self, html: &str) -> Result<()>
pub async fn set_content(&self, html: &str) -> Result<()>
Replace the current document’s content with html.
Sourcepub async fn print_to_pdf(&self, path: &str) -> Result<()>
pub async fn print_to_pdf(&self, path: &str) -> Result<()>
Render the current page to PDF and write it to path.
Sourcepub async fn add_init_script(&self, source: &str) -> Result<String>
pub async fn add_init_script(&self, source: &str) -> Result<String>
Register source to run before every future document on this target
(before any page script runs). Returns an identifier for remove_init_script.
Sourcepub async fn remove_init_script(&self, identifier: &str) -> Result<()>
pub async fn remove_init_script(&self, identifier: &str) -> Result<()>
Unregister a script added via add_init_script.
Sourcepub async fn set_user_agent(&self, ua: &str) -> Result<()>
pub async fn set_user_agent(&self, ua: &str) -> Result<()>
Override the User-Agent header and navigator.userAgent.
Sourcepub async fn set_geolocation(
&self,
latitude: f64,
longitude: f64,
accuracy: f64,
) -> Result<()>
pub async fn set_geolocation( &self, latitude: f64, longitude: f64, accuracy: f64, ) -> Result<()>
Override the geolocation API’s reported position.
Sourcepub async fn set_offline(&self, offline: bool) -> Result<()>
pub async fn set_offline(&self, offline: bool) -> Result<()>
Simulate going offline (or restore normal networking).
Sourcepub async fn set_attribute(
&self,
node_id: i64,
name: &str,
value: &str,
) -> Result<()>
pub async fn set_attribute( &self, node_id: i64, name: &str, value: &str, ) -> Result<()>
Set (or add) an attribute on a DOM node.
Sourcepub async fn set_outer_html(&self, node_id: i64, html: &str) -> Result<()>
pub async fn set_outer_html(&self, node_id: i64, html: &str) -> Result<()>
Replace a DOM node’s outer HTML.
Sourcepub async fn remove_node(&self, node_id: i64) -> Result<()>
pub async fn remove_node(&self, node_id: i64) -> Result<()>
Remove a DOM node from the document.
Sourcepub async fn call_function_on(
&self,
object_id: &str,
function_declaration: &str,
) -> Result<Value>
pub async fn call_function_on( &self, object_id: &str, function_declaration: &str, ) -> Result<Value>
Call function_declaration with the object identified by object_id as this,
returning its result by value.
Navigate to url. Returns as soon as navigation starts, without waiting for
the page to finish loading; use navigate_and_wait
to block until Page.loadEventFired.
A navigation Chrome refused (an unresolvable host, a refused connection, a
blocked request) is a CdpError::Protocol carrying Chrome’s errorText,
not a successful result.
Navigate to url and wait for Page.loadEventFired, up to timeout_ms.
Requires the "Page" domain to be enabled.
Fails the same way navigate does, before waiting for a
load event that a refused navigation would never fire.
Source§impl CdpClient
impl CdpClient
Sourcepub async fn eval(&self, expression: &str) -> Result<String>
pub async fn eval(&self, expression: &str) -> Result<String>
Evaluate a JS expression and return its result stringified.
An expression that throws is a CdpError::Protocol carrying the thrown
message, since a returned string cannot tell an empty result apart from a
failure. Use evaluate when you want the structured
result, or an exception as data rather than as an error.
Sourcepub async fn evaluate(&self, expression: &str) -> Result<EvaluateResult>
pub async fn evaluate(&self, expression: &str) -> Result<EvaluateResult>
Evaluate a JS expression via Runtime.evaluate and return the full result,
including any exception details.
Source§impl CdpClient
impl CdpClient
Sourcepub async fn screenshot(&self) -> Result<Vec<u8>>
pub async fn screenshot(&self) -> Result<Vec<u8>>
Capture a PNG screenshot of the current viewport.
Sourcepub async fn screenshot_to_file(&self, path: &str) -> Result<()>
pub async fn screenshot_to_file(&self, path: &str) -> Result<()>
screenshot, written directly to path.
Sourcepub async fn full_page_screenshot(&self) -> Result<Vec<u8>>
pub async fn full_page_screenshot(&self) -> Result<Vec<u8>>
Capture a PNG screenshot of the full page, resizing the viewport to the page’s scroll size first (restoring it is the caller’s responsibility).
Sourcepub async fn full_page_screenshot_to_file(&self, path: &str) -> Result<()>
pub async fn full_page_screenshot_to_file(&self, path: &str) -> Result<()>
full_page_screenshot, written directly to path.
Source§impl CdpClient
impl CdpClient
Sourcepub fn session(&self, session_id: impl Into<String>) -> CdpSession<'_>
pub fn session(&self, session_id: impl Into<String>) -> CdpSession<'_>
Address commands to a session id obtained elsewhere, e.g. from a
Target.attachedToTarget event raised by setAutoAttach.
Nothing is sent, and the id is not checked; commands simply fail with the browser’s own error if no such session exists.
Sourcepub async fn attach_to_target(&self, target_id: &str) -> Result<CdpSession<'_>>
pub async fn attach_to_target(&self, target_id: &str) -> Result<CdpSession<'_>>
Attach to target_id and return a handle for driving it.
The session shares this client’s connection, its message ids, and its
command timeout. Find target ids with Target.getTargets, or create one
with Target.createTarget, through call.
let session = client.attach_to_target("A1B2C3").await?;
let _: Value = session.call("Runtime.enable", json!({})).await?;
session.detach().await?;Source§impl CdpClient
impl CdpClient
Sourcepub async fn send<C: Command>(&self, params: C) -> Result<C::Returns>
pub async fn send<C: Command>(&self, params: C) -> Result<C::Returns>
Send a typed command and get back its declared result.
The method name and the result type both come from the parameters, so a command cannot be paired with the wrong result.
use cdp_driver::protocol::page::NavigateParams;
let navigated = client
.send(NavigateParams {
url: "https://example.com".to_string(),
..Default::default()
})
.await?;
println!("{}", navigated.frame_id);