Skip to main content

cdp_driver/
network.rs

1//! `Network` and `Fetch` domain commands (cookies, headers, request interception),
2//! added to [`CdpClient`] here.
3
4use std::collections::HashMap;
5
6use serde_json::json;
7
8use crate::client::CdpClient;
9use crate::error::Result;
10
11impl CdpClient {
12    /// Set a cookie. `url` or `domain` is required by CDP to resolve which
13    /// site the cookie belongs to.
14    pub async fn set_cookie(
15        &self,
16        name: &str,
17        value: &str,
18        url: Option<&str>,
19        domain: Option<&str>,
20        path: Option<&str>,
21    ) -> Result<()> {
22        let mut params = json!({ "name": name, "value": value });
23        if let Some(u) = url {
24            params["url"] = json!(u);
25        }
26        if let Some(d) = domain {
27            params["domain"] = json!(d);
28        }
29        if let Some(p) = path {
30            params["path"] = json!(p);
31        }
32        self.send_command("Network.setCookie", params).await?;
33        Ok(())
34    }
35
36    /// Delete cookies matching `name` (and optionally scoped to `url`).
37    pub async fn delete_cookies(&self, name: &str, url: Option<&str>) -> Result<()> {
38        let mut params = json!({ "name": name });
39        if let Some(u) = url {
40            params["url"] = json!(u);
41        }
42        self.send_command("Network.deleteCookies", params).await?;
43        Ok(())
44    }
45
46    /// Send `headers` with every subsequent request from this target.
47    pub async fn set_extra_headers(&self, headers: &HashMap<String, String>) -> Result<()> {
48        self.send_command("Network.setExtraHTTPHeaders", json!({ "headers": headers }))
49            .await?;
50        Ok(())
51    }
52
53    /// Block requests whose URL matches any of `patterns` (CDP wildcard syntax, e.g.
54    /// `"*.example.com/*"`).
55    pub async fn block_urls(&self, patterns: &[&str]) -> Result<()> {
56        self.send_command("Network.setBlockedURLs", json!({ "urls": patterns }))
57            .await?;
58        Ok(())
59    }
60
61    /// Fetch a response body by request id, decoding it if Chrome returned it base64-encoded.
62    pub async fn get_response_body(&self, request_id: &str) -> Result<String> {
63        let result = self
64            .send_command(
65                "Network.getResponseBody",
66                json!({ "requestId": request_id }),
67            )
68            .await?;
69        let body = result["body"].as_str().unwrap_or("").to_string();
70        let encoded = result["base64Encoded"].as_bool().unwrap_or(false);
71        if encoded {
72            use base64::Engine;
73            let bytes = base64::engine::general_purpose::STANDARD
74                .decode(&body)
75                .unwrap_or_default();
76            Ok(String::from_utf8_lossy(&bytes).into_owned())
77        } else {
78            Ok(body)
79        }
80    }
81
82    /// Enable request interception for URLs matching `url_patterns`. Matching requests
83    /// pause and must be resolved with [`continue_request`](Self::continue_request) or
84    /// [`fulfill_request`](Self::fulfill_request), delivered as `Fetch.requestPaused`
85    /// events (see [`subscribe_events`](Self::subscribe_events)).
86    pub async fn intercept_requests(&self, url_patterns: &[&str]) -> Result<()> {
87        self.enable_domain("Fetch").await?;
88        let patterns: Vec<_> = url_patterns
89            .iter()
90            .map(|p| json!({ "urlPattern": p, "requestStage": "Request" }))
91            .collect();
92        self.send_command("Fetch.enable", json!({ "patterns": patterns }))
93            .await?;
94        Ok(())
95    }
96
97    /// Let a paused request proceed unmodified.
98    pub async fn continue_request(&self, request_id: &str) -> Result<()> {
99        self.send_command("Fetch.continueRequest", json!({ "requestId": request_id }))
100            .await?;
101        Ok(())
102    }
103
104    /// Respond to a paused request with a synthetic response instead of letting it
105    /// reach the network.
106    pub async fn fulfill_request(
107        &self,
108        request_id: &str,
109        status: u16,
110        body: &str,
111        content_type: &str,
112    ) -> Result<()> {
113        use base64::Engine;
114        let body_b64 = base64::engine::general_purpose::STANDARD.encode(body);
115        self.send_command(
116            "Fetch.fulfillRequest",
117            json!({
118                "requestId":       request_id,
119                "responseCode":    status,
120                "body":            body_b64,
121                "responseHeaders": [{ "name": "content-type", "value": content_type }],
122            }),
123        )
124        .await?;
125        Ok(())
126    }
127}