Skip to main content

cdp_driver/
page.rs

1//! `Page`, `Emulation`, and `DOM` mutation commands, added to [`CdpClient`] here.
2
3use serde_json::json;
4use tokio::sync::broadcast;
5
6use crate::client::CdpClient;
7use crate::error::{CdpError, Result};
8use crate::types::NavigationResult;
9
10/// Judge a `Page.navigate` result. Chrome answers a navigation it could not
11/// perform with a frame id, a loader id and an `errorText`, so a result that
12/// looks complete still has to be read as a failure.
13fn navigation_outcome(url: &str, navigation: NavigationResult) -> Result<NavigationResult> {
14    match &navigation.error_text {
15        Some(reason) => Err(CdpError::Protocol(format!(
16            "navigation to {url} failed: {reason}"
17        ))),
18        None => Ok(navigation),
19    }
20}
21
22impl CdpClient {
23    /// Replace the current document's content with `html`.
24    pub async fn set_content(&self, html: &str) -> Result<()> {
25        let frame_id = {
26            let result = self.send_command("Page.getFrameTree", json!({})).await?;
27            result["frameTree"]["frame"]["id"]
28                .as_str()
29                .unwrap_or("")
30                .to_string()
31        };
32        self.send_command(
33            "Page.setDocumentContent",
34            json!({
35                "frameId": frame_id,
36                "html":    html,
37            }),
38        )
39        .await?;
40        Ok(())
41    }
42
43    /// Render the current page to PDF and write it to `path`.
44    pub async fn print_to_pdf(&self, path: &str) -> Result<()> {
45        let result = self
46            .send_command(
47                "Page.printToPDF",
48                json!({
49                    "printBackground": true,
50                }),
51            )
52            .await?;
53        let data = result["data"].as_str().unwrap_or("");
54        use base64::Engine;
55        let bytes = base64::engine::general_purpose::STANDARD
56            .decode(data)
57            .map_err(|e| crate::error::CdpError::Protocol(e.to_string()))?;
58        tokio::fs::write(path, bytes).await?;
59        Ok(())
60    }
61
62    /// Register `source` to run before every future document on this target
63    /// (before any page script runs). Returns an identifier for [`remove_init_script`](Self::remove_init_script).
64    pub async fn add_init_script(&self, source: &str) -> Result<String> {
65        let result = self
66            .send_command(
67                "Page.addScriptToEvaluateOnNewDocument",
68                json!({ "source": source }),
69            )
70            .await?;
71        Ok(result["identifier"].as_str().unwrap_or("").to_string())
72    }
73
74    /// Unregister a script added via [`add_init_script`](Self::add_init_script).
75    pub async fn remove_init_script(&self, identifier: &str) -> Result<()> {
76        self.send_command(
77            "Page.removeScriptToEvaluateOnNewDocument",
78            json!({ "identifier": identifier }),
79        )
80        .await?;
81        Ok(())
82    }
83
84    /// Override the `User-Agent` header and `navigator.userAgent`.
85    pub async fn set_user_agent(&self, ua: &str) -> Result<()> {
86        self.send_command("Emulation.setUserAgentOverride", json!({ "userAgent": ua }))
87            .await?;
88        Ok(())
89    }
90
91    /// Override the geolocation API's reported position.
92    pub async fn set_geolocation(
93        &self,
94        latitude: f64,
95        longitude: f64,
96        accuracy: f64,
97    ) -> Result<()> {
98        self.send_command(
99            "Emulation.setGeolocationOverride",
100            json!({
101                "latitude":  latitude,
102                "longitude": longitude,
103                "accuracy":  accuracy,
104            }),
105        )
106        .await?;
107        Ok(())
108    }
109
110    /// Simulate going offline (or restore normal networking).
111    pub async fn set_offline(&self, offline: bool) -> Result<()> {
112        self.send_command(
113            "Network.emulateNetworkConditions",
114            json!({
115                "offline":            offline,
116                "latency":            0,
117                "downloadThroughput": -1,
118                "uploadThroughput":   -1,
119            }),
120        )
121        .await?;
122        Ok(())
123    }
124
125    /// Set (or add) an attribute on a DOM node.
126    pub async fn set_attribute(&self, node_id: i64, name: &str, value: &str) -> Result<()> {
127        self.send_command(
128            "DOM.setAttributeValue",
129            json!({
130                "nodeId": node_id,
131                "name":   name,
132                "value":  value,
133            }),
134        )
135        .await?;
136        Ok(())
137    }
138
139    /// Replace a DOM node's outer HTML.
140    pub async fn set_outer_html(&self, node_id: i64, html: &str) -> Result<()> {
141        self.send_command(
142            "DOM.setOuterHTML",
143            json!({
144                "nodeId":    node_id,
145                "outerHTML": html,
146            }),
147        )
148        .await?;
149        Ok(())
150    }
151
152    /// Remove a DOM node from the document.
153    pub async fn remove_node(&self, node_id: i64) -> Result<()> {
154        self.send_command("DOM.removeNode", json!({ "nodeId": node_id }))
155            .await?;
156        Ok(())
157    }
158
159    /// Call `function_declaration` with the object identified by `object_id` as `this`,
160    /// returning its result by value.
161    pub async fn call_function_on(
162        &self,
163        object_id: &str,
164        function_declaration: &str,
165    ) -> Result<serde_json::Value> {
166        let result = self
167            .send_command(
168                "Runtime.callFunctionOn",
169                json!({
170                    "objectId":            object_id,
171                    "functionDeclaration": function_declaration,
172                    "returnByValue":       true,
173                }),
174            )
175            .await?;
176        Ok(result["result"]["value"].clone())
177    }
178
179    /// Navigate to `url`. Returns as soon as navigation starts, without waiting for
180    /// the page to finish loading; use [`navigate_and_wait`](Self::navigate_and_wait)
181    /// to block until `Page.loadEventFired`.
182    ///
183    /// A navigation Chrome refused (an unresolvable host, a refused connection, a
184    /// blocked request) is a [`CdpError::Protocol`] carrying Chrome's `errorText`,
185    /// not a successful result.
186    pub async fn navigate(&self, url: &str) -> Result<NavigationResult> {
187        let result = self
188            .send_command("Page.navigate", json!({ "url": url }))
189            .await?;
190        navigation_outcome(url, serde_json::from_value(result)?)
191    }
192
193    /// Navigate to `url` and wait for `Page.loadEventFired`, up to `timeout_ms`.
194    /// Requires the `"Page"` domain to be enabled.
195    ///
196    /// Fails the same way [`navigate`](Self::navigate) does, before waiting for a
197    /// load event that a refused navigation would never fire.
198    pub async fn navigate_and_wait(&self, url: &str, timeout_ms: u64) -> Result<NavigationResult> {
199        let mut rx = self.subscribe_events();
200        let nav = self.navigate(url).await?;
201        tokio::time::timeout(std::time::Duration::from_millis(timeout_ms), async move {
202            loop {
203                match rx.recv().await {
204                    Ok((m, _)) if m == "Page.loadEventFired" => return Ok(nav),
205                    Ok(_) => continue,
206                    Err(broadcast::error::RecvError::Lagged(_)) => continue,
207                    Err(_) => return Err(CdpError::Protocol("event channel closed".into())),
208                }
209            }
210        })
211        .await
212        .map_err(|_| CdpError::Timeout)?
213    }
214
215    /// Override the viewport size and mobile emulation flag.
216    pub async fn set_viewport(&self, width: i32, height: i32, mobile: bool) -> Result<()> {
217        self.send_command(
218            "Emulation.setDeviceMetricsOverride",
219            json!({ "width": width, "height": height, "deviceScaleFactor": 1, "mobile": mobile }),
220        )
221        .await?;
222        Ok(())
223    }
224}