Skip to main content

cdp_driver/
runtime.rs

1//! Evaluating JavaScript in the page.
2
3use serde_json::{Value, json};
4
5use crate::client::CdpClient;
6use crate::error::{CdpError, Result};
7use crate::types::EvaluateResult;
8
9/// What to say about an expression that threw, given Chrome's `exceptionDetails`.
10///
11/// A thrown `Error` arrives as an object whose `description` is its message
12/// followed by a stack trace, so only the first line is kept. Anything else JS
13/// can throw (a string, a number) arrives as a plain `value` instead, and if
14/// Chrome sends neither, its own summary `text` is all there is.
15fn thrown_message(details: &Value) -> String {
16    let exception = &details["exception"];
17    if let Some(description) = exception["description"].as_str() {
18        return description
19            .lines()
20            .next()
21            .unwrap_or(description)
22            .to_string();
23    }
24    match &exception["value"] {
25        Value::Null => details["text"].as_str().unwrap_or("uncaught").to_string(),
26        Value::String(thrown) => thrown.clone(),
27        thrown => thrown.to_string(),
28    }
29}
30
31impl CdpClient {
32    /// Evaluate a JS expression and return its result stringified.
33    ///
34    /// An expression that throws is a [`CdpError::Protocol`] carrying the thrown
35    /// message, since a returned string cannot tell an empty result apart from a
36    /// failure. Use [`evaluate`](Self::evaluate) when you want the structured
37    /// result, or an exception as data rather than as an error.
38    pub async fn eval(&self, expression: &str) -> Result<String> {
39        let outcome = self.evaluate(expression).await?;
40        if let Some(details) = &outcome.exception_details {
41            return Err(CdpError::Protocol(format!(
42                "evaluation threw: {}",
43                thrown_message(details)
44            )));
45        }
46        Ok(outcome
47            .result
48            .value
49            .map(|v| match v {
50                Value::String(s) => s,
51                other => other.to_string(),
52            })
53            .unwrap_or_default())
54    }
55
56    /// Evaluate a JS expression via `Runtime.evaluate` and return the full result,
57    /// including any exception details.
58    pub async fn evaluate(&self, expression: &str) -> Result<EvaluateResult> {
59        let result = self
60            .send_command(
61                "Runtime.evaluate",
62                json!({ "expression": expression, "returnByValue": true }),
63            )
64            .await?;
65        Ok(serde_json::from_value(result)?)
66    }
67}