1use base64::Engine;
4use serde_json::{Value, json};
5
6use crate::client::CdpClient;
7use crate::error::{CdpError, Result};
8
9const FALLBACK_VIEWPORT_WIDTH: i32 = 1920;
12
13const FALLBACK_VIEWPORT_HEIGHT: i32 = 1200;
15
16fn png_bytes_from(result: &Value) -> Result<Vec<u8>> {
18 let data = result["data"]
19 .as_str()
20 .ok_or_else(|| CdpError::Protocol("screenshot response has no data".into()))?;
21 base64::engine::general_purpose::STANDARD
22 .decode(data)
23 .map_err(|e| CdpError::Protocol(e.to_string()))
24}
25
26impl CdpClient {
27 pub async fn screenshot(&self) -> Result<Vec<u8>> {
29 let result = self
30 .send_command(
31 "Page.captureScreenshot",
32 json!({ "format": "png", "fromSurface": true }),
33 )
34 .await?;
35 png_bytes_from(&result)
36 }
37
38 pub async fn screenshot_to_file(&self, path: &str) -> Result<()> {
40 tokio::fs::write(path, self.screenshot().await?).await?;
41 Ok(())
42 }
43
44 pub async fn full_page_screenshot(&self) -> Result<Vec<u8>> {
47 let size = self
48 .evaluate(
49 "(() => ({ \
50 w: Math.max(document.body.scrollWidth, document.documentElement.scrollWidth), \
51 h: Math.max(document.body.scrollHeight, document.documentElement.scrollHeight) \
52 }))()",
53 )
54 .await?;
55
56 let dims = size.result.value.as_ref();
57 let w = dims
58 .and_then(|v| v["w"].as_i64())
59 .unwrap_or(FALLBACK_VIEWPORT_WIDTH as i64) as i32;
60 let h = dims
61 .and_then(|v| v["h"].as_i64())
62 .unwrap_or(FALLBACK_VIEWPORT_HEIGHT as i64) as i32;
63 self.set_viewport(
64 w.max(FALLBACK_VIEWPORT_WIDTH),
65 h.max(FALLBACK_VIEWPORT_HEIGHT),
66 false,
67 )
68 .await?;
69
70 let result = self
71 .send_command(
72 "Page.captureScreenshot",
73 json!({
74 "format": "png",
75 "captureBeyondViewport": true,
76 "fromSurface": true,
77 }),
78 )
79 .await?;
80 png_bytes_from(&result)
81 }
82
83 pub async fn full_page_screenshot_to_file(&self, path: &str) -> Result<()> {
85 tokio::fs::write(path, self.full_page_screenshot().await?).await?;
86 Ok(())
87 }
88}