Skip to main content

cdp_driver/
dom.rs

1//! Reading the document tree.
2
3use serde_json::json;
4
5use crate::client::CdpClient;
6use crate::error::{CdpError, Result};
7use crate::types::DocumentNode;
8
9impl CdpClient {
10    /// Fetch the document's root node. Requires the `"DOM"` domain to be enabled.
11    pub async fn get_document(&self) -> Result<DocumentNode> {
12        let result = self
13            .send_command("DOM.getDocument", json!({ "depth": 0 }))
14            .await?;
15        let root = result["root"].clone();
16        if root.is_null() {
17            return Err(CdpError::Protocol(
18                "DOM.getDocument returned no root".into(),
19            ));
20        }
21        Ok(serde_json::from_value(root)?)
22    }
23
24    /// Returns the matched `nodeId`, or `None` when nothing matches.
25    /// CDP reports a missing match as `nodeId` 0; this surfaces that as `None`
26    /// rather than a node id that looks valid.
27    pub async fn query_selector(&self, node_id: i64, selector: &str) -> Result<Option<i64>> {
28        let result = self
29            .send_command(
30                "DOM.querySelector",
31                json!({ "nodeId": node_id, "selector": selector }),
32            )
33            .await?;
34        Ok(match result["nodeId"].as_i64() {
35            Some(id) if id > 0 => Some(id),
36            _ => None,
37        })
38    }
39
40    /// Serialize a node's outer HTML.
41    pub async fn get_outer_html(&self, node_id: i64) -> Result<String> {
42        let result = self
43            .send_command("DOM.getOuterHTML", json!({ "nodeId": node_id }))
44            .await?;
45        Ok(result["outerHTML"].as_str().unwrap_or("").to_string())
46    }
47}