Skip to main content

cdp_driver/
page.rs

1//! `Page`, `Emulation`, and `DOM` mutation commands, added to [`CdpClient`] here.
2
3use serde_json::json;
4
5use crate::client::CdpClient;
6use crate::error::Result;
7
8impl CdpClient {
9    /// Replace the current document's content with `html`.
10    pub async fn set_content(&self, html: &str) -> Result<()> {
11        let frame_id = {
12            let result = self.send_command("Page.getFrameTree", json!({})).await?;
13            result["frameTree"]["frame"]["id"]
14                .as_str()
15                .unwrap_or("")
16                .to_string()
17        };
18        self.send_command(
19            "Page.setDocumentContent",
20            json!({
21                "frameId": frame_id,
22                "html":    html,
23            }),
24        )
25        .await?;
26        Ok(())
27    }
28
29    /// Render the current page to PDF and write it to `path`.
30    pub async fn print_to_pdf(&self, path: &str) -> Result<()> {
31        let result = self
32            .send_command(
33                "Page.printToPDF",
34                json!({
35                    "printBackground": true,
36                }),
37            )
38            .await?;
39        let data = result["data"].as_str().unwrap_or("");
40        use base64::Engine;
41        let bytes = base64::engine::general_purpose::STANDARD
42            .decode(data)
43            .map_err(|e| crate::error::CdpError::Protocol(e.to_string()))?;
44        tokio::fs::write(path, bytes).await?;
45        Ok(())
46    }
47
48    /// Register `source` to run before every future document on this target
49    /// (before any page script runs). Returns an identifier for [`remove_init_script`](Self::remove_init_script).
50    pub async fn add_init_script(&self, source: &str) -> Result<String> {
51        let result = self
52            .send_command(
53                "Page.addScriptToEvaluateOnNewDocument",
54                json!({ "source": source }),
55            )
56            .await?;
57        Ok(result["identifier"].as_str().unwrap_or("").to_string())
58    }
59
60    /// Unregister a script added via [`add_init_script`](Self::add_init_script).
61    pub async fn remove_init_script(&self, identifier: &str) -> Result<()> {
62        self.send_command(
63            "Page.removeScriptToEvaluateOnNewDocument",
64            json!({ "identifier": identifier }),
65        )
66        .await?;
67        Ok(())
68    }
69
70    /// Override the `User-Agent` header and `navigator.userAgent`.
71    pub async fn set_user_agent(&self, ua: &str) -> Result<()> {
72        self.send_command("Emulation.setUserAgentOverride", json!({ "userAgent": ua }))
73            .await?;
74        Ok(())
75    }
76
77    /// Override the geolocation API's reported position.
78    pub async fn set_geolocation(
79        &self,
80        latitude: f64,
81        longitude: f64,
82        accuracy: f64,
83    ) -> Result<()> {
84        self.send_command(
85            "Emulation.setGeolocationOverride",
86            json!({
87                "latitude":  latitude,
88                "longitude": longitude,
89                "accuracy":  accuracy,
90            }),
91        )
92        .await?;
93        Ok(())
94    }
95
96    /// Simulate going offline (or restore normal networking).
97    pub async fn set_offline(&self, offline: bool) -> Result<()> {
98        self.send_command(
99            "Network.emulateNetworkConditions",
100            json!({
101                "offline":            offline,
102                "latency":            0,
103                "downloadThroughput": -1,
104                "uploadThroughput":   -1,
105            }),
106        )
107        .await?;
108        Ok(())
109    }
110
111    /// Set (or add) an attribute on a DOM node.
112    pub async fn set_attribute(&self, node_id: i64, name: &str, value: &str) -> Result<()> {
113        self.send_command(
114            "DOM.setAttributeValue",
115            json!({
116                "nodeId": node_id,
117                "name":   name,
118                "value":  value,
119            }),
120        )
121        .await?;
122        Ok(())
123    }
124
125    /// Replace a DOM node's outer HTML.
126    pub async fn set_outer_html(&self, node_id: i64, html: &str) -> Result<()> {
127        self.send_command(
128            "DOM.setOuterHTML",
129            json!({
130                "nodeId":    node_id,
131                "outerHTML": html,
132            }),
133        )
134        .await?;
135        Ok(())
136    }
137
138    /// Remove a DOM node from the document.
139    pub async fn remove_node(&self, node_id: i64) -> Result<()> {
140        self.send_command("DOM.removeNode", json!({ "nodeId": node_id }))
141            .await?;
142        Ok(())
143    }
144
145    /// Call `function_declaration` with the object identified by `object_id` as `this`,
146    /// returning its result by value.
147    pub async fn call_function_on(
148        &self,
149        object_id: &str,
150        function_declaration: &str,
151    ) -> Result<serde_json::Value> {
152        let result = self
153            .send_command(
154                "Runtime.callFunctionOn",
155                json!({
156                    "objectId":            object_id,
157                    "functionDeclaration": function_declaration,
158                    "returnByValue":       true,
159                }),
160            )
161            .await?;
162        Ok(result["result"]["value"].clone())
163    }
164}