chromiumoxide/
js.rs

1use serde::de::DeserializeOwned;
2
3use chromiumoxide_cdp::cdp::js_protocol::runtime::{
4    CallFunctionOnParams, EvaluateParams, RemoteObject,
5};
6
7use crate::utils::is_likely_js_function;
8
9#[derive(Debug, Clone)]
10pub struct EvaluationResult {
11    /// Mirror object referencing original JavaScript object
12    inner: RemoteObject,
13}
14
15impl EvaluationResult {
16    /// Creates a new evaluation result from a remote object.
17    pub fn new(inner: RemoteObject) -> Self {
18        Self { inner }
19    }
20    /// Get a reference to the underlying remote object.
21    pub fn object(&self) -> &RemoteObject {
22        &self.inner
23    }
24
25    /// Get the deserialized value if available.
26    pub fn value(&self) -> Option<&serde_json::Value> {
27        self.object().value.as_ref()
28    }
29
30    /// Attempts to deserialize the value into the given type
31    pub fn into_value<T: DeserializeOwned>(self) -> serde_json::Result<T> {
32        let value = self
33            .inner
34            .value
35            .ok_or_else(|| serde::de::Error::custom("No value found"))?;
36        serde_json::from_value(value)
37    }
38
39    /// Attempts to deserialize the value into as bytes.
40    pub fn into_bytes(self) -> serde_json::Result<Vec<u8>> {
41        let value = self
42            .inner
43            .value
44            .ok_or_else(|| serde::de::Error::custom("No value found"))?;
45
46        Ok(value.as_str().unwrap_or_default().into())
47    }
48}
49
50#[derive(Debug, Clone)]
51pub enum Evaluation {
52    /// A JavaScript expression to evaluate.
53    Expression(EvaluateParams),
54    /// A JavaScript function to invoke.
55    Function(CallFunctionOnParams),
56}
57
58impl From<&str> for Evaluation {
59    fn from(expression: &str) -> Self {
60        if is_likely_js_function(expression) {
61            CallFunctionOnParams::from(expression).into()
62        } else {
63            EvaluateParams::from(expression).into()
64        }
65    }
66}
67
68impl From<String> for Evaluation {
69    fn from(expression: String) -> Self {
70        expression.as_str().into()
71    }
72}
73
74impl From<EvaluateParams> for Evaluation {
75    fn from(params: EvaluateParams) -> Self {
76        Evaluation::Expression(params)
77    }
78}
79
80impl From<CallFunctionOnParams> for Evaluation {
81    fn from(params: CallFunctionOnParams) -> Self {
82        Evaluation::Function(params)
83    }
84}