Skip to main content

cdp_driver/
screenshot.rs

1//! Capturing the page as a PNG.
2
3use base64::Engine;
4use serde_json::{Value, json};
5
6use crate::client::CdpClient;
7use crate::error::{CdpError, Result};
8
9/// Used when the page reports no scroll size of its own, and as a floor so a
10/// full-page capture is never smaller than an ordinary viewport.
11const FALLBACK_VIEWPORT_WIDTH: i32 = 1920;
12
13/// The height counterpart of [`FALLBACK_VIEWPORT_WIDTH`].
14const FALLBACK_VIEWPORT_HEIGHT: i32 = 1200;
15
16/// Decode the base64 payload a screenshot command answers with.
17fn 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    /// Capture a PNG screenshot of the current viewport.
28    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    /// [`screenshot`](Self::screenshot), written directly to `path`.
39    pub async fn screenshot_to_file(&self, path: &str) -> Result<()> {
40        tokio::fs::write(path, self.screenshot().await?).await?;
41        Ok(())
42    }
43
44    /// Capture a PNG screenshot of the full page, resizing the viewport to the
45    /// page's scroll size first (restoring it is the caller's responsibility).
46    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    /// [`full_page_screenshot`](Self::full_page_screenshot), written directly to `path`.
84    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}