1use serde_json::json;
4use tokio::sync::broadcast;
5
6use crate::client::CdpClient;
7use crate::error::{CdpError, Result};
8use crate::types::NavigationResult;
9
10fn 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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}