Skip to main content

CdpClient

Struct CdpClient 

Source
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

Source

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.

Source

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).

Source

pub fn command_timeout(&self) -> Duration

The current per-command timeout.

Source

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?;
Source

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.

Source

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.

Source

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).

Source

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.

Source

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

pub async fn close(&self) -> Result<()>

Close the tab this client is attached to.

Source§

impl CdpClient

Source

pub async fn get_version(host: &str, port: u16) -> Result<BrowserVersion>

GET /json/version on Chrome’s debugging HTTP endpoint.

Source

pub async fn list_targets(host: &str, port: u16) -> Result<Vec<Target>>

GET /json/list: enumerate debuggable targets (tabs, workers, …).

Source

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

pub async fn create_tab( host: &str, port: u16, url: Option<&str>, ) -> Result<Target>

Open a new tab, optionally navigating it to url immediately. Uses PUT /json/new since modern Chrome rejects GET for this endpoint.

Source§

impl CdpClient

Source

pub async fn get_document(&self) -> Result<DocumentNode>

Fetch the document’s root node. Requires the "DOM" domain to be enabled.

Source

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.

Source

pub async fn get_outer_html(&self, node_id: i64) -> Result<String>

Serialize a node’s outer HTML.

Source§

impl CdpClient

Set a cookie. url or domain is required by CDP to resolve which site the cookie belongs to.

Source

pub async fn delete_cookies(&self, name: &str, url: Option<&str>) -> Result<()>

Delete cookies matching name (and optionally scoped to url).

Source

pub async fn set_extra_headers( &self, headers: &HashMap<String, String>, ) -> Result<()>

Send headers with every subsequent request from this target.

Source

pub async fn block_urls(&self, patterns: &[&str]) -> Result<()>

Block requests whose URL matches any of patterns (CDP wildcard syntax, e.g. "*.example.com/*").

Source

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.

Source

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).

Source

pub async fn continue_request(&self, request_id: &str) -> Result<()>

Let a paused request proceed unmodified.

Source

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.

Source

pub async fn get_cookies(&self) -> Result<Vec<Cookie>>

List cookies visible to the current page.

Source§

impl CdpClient

Source

pub async fn set_content(&self, html: &str) -> Result<()>

Replace the current document’s content with html.

Source

pub async fn print_to_pdf(&self, path: &str) -> Result<()>

Render the current page to PDF and write it to path.

Source

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.

Source

pub async fn remove_init_script(&self, identifier: &str) -> Result<()>

Unregister a script added via add_init_script.

Source

pub async fn set_user_agent(&self, ua: &str) -> Result<()>

Override the User-Agent header and navigator.userAgent.

Source

pub async fn set_geolocation( &self, latitude: f64, longitude: f64, accuracy: f64, ) -> Result<()>

Override the geolocation API’s reported position.

Source

pub async fn set_offline(&self, offline: bool) -> Result<()>

Simulate going offline (or restore normal networking).

Source

pub async fn set_attribute( &self, node_id: i64, name: &str, value: &str, ) -> Result<()>

Set (or add) an attribute on a DOM node.

Source

pub async fn set_outer_html(&self, node_id: i64, html: &str) -> Result<()>

Replace a DOM node’s outer HTML.

Source

pub async fn remove_node(&self, node_id: i64) -> Result<()>

Remove a DOM node from the document.

Source

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.

Source

pub async fn navigate(&self, url: &str) -> Result<NavigationResult>

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.

Source

pub async fn navigate_and_wait( &self, url: &str, timeout_ms: u64, ) -> Result<NavigationResult>

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

pub async fn set_viewport( &self, width: i32, height: i32, mobile: bool, ) -> Result<()>

Override the viewport size and mobile emulation flag.

Source§

impl CdpClient

Source

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.

Source

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

Source

pub async fn screenshot(&self) -> Result<Vec<u8>>

Capture a PNG screenshot of the current viewport.

Source

pub async fn screenshot_to_file(&self, path: &str) -> Result<()>

screenshot, written directly to path.

Source

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).

Source

pub async fn full_page_screenshot_to_file(&self, path: &str) -> Result<()>

full_page_screenshot, written directly to path.

Source§

impl CdpClient

Source

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.

Source

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

Source

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);
Source

pub async fn wait_for<E: Event>(&self, timeout_ms: u64) -> Result<E>

Wait for the next E on the connected target, up to timeout_ms milliseconds.

The event’s domain has to be enabled first, as with wait_for_event.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more