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