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    pub fn new(inner: RemoteObject) -> Self {
17        Self { inner }
18    }
19
20    pub fn object(&self) -> &RemoteObject {
21        &self.inner
22    }
23
24    pub fn value(&self) -> Option<&serde_json::Value> {
25        self.object().value.as_ref()
26    }
27
28    /// Attempts to deserialize the value into the given type
29    pub fn into_value<T: DeserializeOwned>(self) -> serde_json::Result<T> {
30        let value = self
31            .inner
32            .value
33            .ok_or_else(|| serde::de::Error::custom("No value found"))?;
34        serde_json::from_value(value)
35    }
36}
37
38#[derive(Debug, Clone)]
39pub enum Evaluation {
40    Expression(EvaluateParams),
41    Function(CallFunctionOnParams),
42}
43
44impl From<&str> for Evaluation {
45    fn from(expression: &str) -> Self {
46        if is_likely_js_function(expression) {
47            CallFunctionOnParams::from(expression).into()
48        } else {
49            EvaluateParams::from(expression).into()
50        }
51    }
52}
53
54impl From<String> for Evaluation {
55    fn from(expression: String) -> Self {
56        expression.as_str().into()
57    }
58}
59
60impl From<EvaluateParams> for Evaluation {
61    fn from(params: EvaluateParams) -> Self {
62        Evaluation::Expression(params)
63    }
64}
65
66impl From<CallFunctionOnParams> for Evaluation {
67    fn from(params: CallFunctionOnParams) -> Self {
68        Evaluation::Function(params)
69    }
70}