Skip to main content

cdp_driver/
discovery.rs

1//! Finding a browser and its targets over Chrome's HTTP endpoint.
2//!
3//! These are the only calls in the crate that speak HTTP rather than CDP: they
4//! are how a caller gets a WebSocket URL to open a session with in the first
5//! place.
6
7use crate::client::CdpClient;
8use crate::error::{CdpError, Result};
9use crate::types::{BrowserVersion, Target};
10
11impl CdpClient {
12    /// `GET /json/version` on Chrome's debugging HTTP endpoint.
13    pub async fn get_version(host: &str, port: u16) -> Result<BrowserVersion> {
14        let url = format!("http://{host}:{port}/json/version");
15        Ok(reqwest::get(&url).await?.json().await?)
16    }
17
18    /// `GET /json/list`: enumerate debuggable targets (tabs, workers, ...).
19    pub async fn list_targets(host: &str, port: u16) -> Result<Vec<Target>> {
20        let url = format!("http://{host}:{port}/json/list");
21        Ok(reqwest::get(&url).await?.json().await?)
22    }
23
24    /// Connect to the first target of type `"page"` reported by [`list_targets`](Self::list_targets).
25    /// Returns [`CdpError::NoTarget`] if none exists.
26    pub async fn connect_to_page(host: &str, port: u16) -> Result<Self> {
27        let targets = Self::list_targets(host, port).await?;
28        let page = targets
29            .into_iter()
30            .find(|t| t.target_type == "page")
31            .ok_or(CdpError::NoTarget)?;
32        let ws_url = page
33            .web_socket_debugger_url
34            .ok_or_else(|| CdpError::InvalidUrl("target has no debugger URL".into()))?;
35        Self::connect(&ws_url).await
36    }
37
38    /// Open a new tab, optionally navigating it to `url` immediately. Uses `PUT
39    /// /json/new` since modern Chrome rejects `GET` for this endpoint.
40    pub async fn create_tab(host: &str, port: u16, url: Option<&str>) -> Result<Target> {
41        // Chrome requires PUT for /json/new (GET returns 405 in modern versions)
42        let endpoint = match url {
43            Some(u) => format!("http://{host}:{port}/json/new?{u}"),
44            None => format!("http://{host}:{port}/json/new"),
45        };
46        Ok(reqwest::Client::new()
47            .put(&endpoint)
48            .send()
49            .await?
50            .json()
51            .await?)
52    }
53}