viewpoint_core/page/
page_info.rs

1//! Page information methods.
2//!
3//! This module contains methods for retrieving page properties like URL and title.
4
5use viewpoint_js::js;
6
7use super::Page;
8use crate::error::PageError;
9
10impl Page {
11    /// Get the current page URL.
12    ///
13    /// # Errors
14    ///
15    /// Returns an error if the page is closed or the evaluation fails.
16    pub async fn url(&self) -> Result<String, PageError> {
17        if self.closed {
18            return Err(PageError::Closed);
19        }
20
21        let result: viewpoint_cdp::protocol::runtime::EvaluateResult = self
22            .connection
23            .send_command(
24                "Runtime.evaluate",
25                Some(viewpoint_cdp::protocol::runtime::EvaluateParams {
26                    expression: js! { window.location.href }.to_string(),
27                    object_group: None,
28                    include_command_line_api: None,
29                    silent: Some(true),
30                    context_id: None,
31                    return_by_value: Some(true),
32                    await_promise: Some(false),
33                }),
34                Some(&self.session_id),
35            )
36            .await?;
37
38        result
39            .result
40            .value
41            .and_then(|v| v.as_str().map(std::string::ToString::to_string))
42            .ok_or_else(|| PageError::EvaluationFailed("Failed to get URL".to_string()))
43    }
44
45    /// Get the current page title.
46    ///
47    /// # Errors
48    ///
49    /// Returns an error if the page is closed or the evaluation fails.
50    pub async fn title(&self) -> Result<String, PageError> {
51        if self.closed {
52            return Err(PageError::Closed);
53        }
54
55        let result: viewpoint_cdp::protocol::runtime::EvaluateResult = self
56            .connection
57            .send_command(
58                "Runtime.evaluate",
59                Some(viewpoint_cdp::protocol::runtime::EvaluateParams {
60                    expression: "document.title".to_string(),
61                    object_group: None,
62                    include_command_line_api: None,
63                    silent: Some(true),
64                    context_id: None,
65                    return_by_value: Some(true),
66                    await_promise: Some(false),
67                }),
68                Some(&self.session_id),
69            )
70            .await?;
71
72        result
73            .result
74            .value
75            .and_then(|v| v.as_str().map(std::string::ToString::to_string))
76            .ok_or_else(|| PageError::EvaluationFailed("Failed to get title".to_string()))
77    }
78}