zendriver 0.2.11

Async-first, undetectable browser automation via the Chrome DevTools Protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//! [`Element`] read methods: attribute access, inner/outer markup, layout
//! geometry, and visibility/enabled state.
//!
//! Each method routes through an internal "refresh on stale" wrapper so a
//! stale CDP handle (post-navigation, post-React-rerender) triggers exactly
//! one transparent re-resolve and retry. `is_visible` and `is_enabled` are
//! thin wrappers around the actionability predicates that the actionability
//! gate also consumes — keeping a single source of truth for "what counts
//! as visible/enabled."
//!
//! `bounding_box` returns a viewport-relative [`BoundingBox`] derived from
//! the `content` quad of `DOM.getBoxModel`. Returns `Ok(None)` when the
//! node has no box (e.g. `display: none`) — Chrome surfaces this as a
//! `-32000 "Could not compute box model"` Cdp error rather than a stale-node
//! signal, so we map that specific error to `None` instead of bubbling.
//! `bounding_box_page` layers `window.scrollX` / `scrollY` on top of that
//! box to yield document-relative ([`PageBox`]) coordinates.

use std::collections::HashMap;

use serde_json::{Value, json};

use crate::element::Element;
use crate::error::{Result, ZendriverError};
use crate::query::actionability;
use crate::query::{BoundingBox, PageBox};

impl Element {
    /// Return the value of attribute `name`, or `None` when absent.
    ///
    /// Routes through `el.getAttribute(name)` in JS so HTML attributes
    /// (`href`, `data-*`) and ARIA attributes resolve identically to user
    /// code reading them in DevTools.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # let tab = browser.main_tab();
    /// let link = tab.find().css("a").one().await?;
    /// if let Some(href) = link.attr("href").await? {
    ///     println!("link goes to {href}");
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn attr(&self, name: impl AsRef<str>) -> Result<Option<String>> {
        let name = name.as_ref().to_string();
        self.with_refresh(|| {
            let name = name.clone();
            async move {
                let res = self
                    .call_on(
                        "function(n){ return this.getAttribute(n); }",
                        json!([{ "value": name }]),
                    )
                    .await?;
                // `getAttribute` returns `null` for missing attributes →
                // `value` field is missing/null on the RemoteObject.
                match res.get("value") {
                    Some(Value::String(s)) => Ok(Some(s.clone())),
                    _ => Ok(None),
                }
            }
        })
        .await
    }

    /// Return a snapshot of every attribute on the element.
    ///
    /// Built from `el.attributes` (live `NamedNodeMap`) on the JS side,
    /// materialized into a plain object before crossing the CDP boundary
    /// so `returnByValue` can serialize it.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # let tab = browser.main_tab();
    /// let el = tab.find().css("input").one().await?;
    /// for (k, v) in el.attrs().await? {
    ///     println!("{k}={v}");
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn attrs(&self) -> Result<HashMap<String, String>> {
        self.with_refresh(|| async move {
            let js = r"
                function() {
                    const out = {};
                    for (const a of this.attributes) { out[a.name] = a.value; }
                    return out;
                }
            ";
            let res = self.call_on(js, json!([])).await?;
            let value = res.get("value").cloned().unwrap_or(Value::Null);
            let obj = value.as_object().cloned().unwrap_or_default();
            let mut out = HashMap::with_capacity(obj.len());
            for (k, v) in obj {
                if let Some(s) = v.as_str() {
                    out.insert(k, s.to_string());
                }
            }
            Ok(out)
        })
        .await
    }

    /// Return the element's `innerText` (rendered text, excluding hidden
    /// subtrees).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # let tab = browser.main_tab();
    /// let h1 = tab.find().css("h1").one().await?;
    /// assert_eq!(h1.inner_text().await?, "Example Domain");
    /// # Ok(()) }
    /// ```
    pub async fn inner_text(&self) -> Result<String> {
        self.with_refresh(|| async move {
            let res = self
                .call_on("function(){ return this.innerText; }", json!([]))
                .await?;
            Ok(res["value"].as_str().unwrap_or("").to_string())
        })
        .await
    }

    /// Return the element's `innerHTML` (serialized child markup).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # let tab = browser.main_tab();
    /// let div = tab.find().css("div.content").one().await?;
    /// println!("{}", div.inner_html().await?);
    /// # Ok(()) }
    /// ```
    pub async fn inner_html(&self) -> Result<String> {
        self.with_refresh(|| async move {
            let res = self
                .call_on("function(){ return this.innerHTML; }", json!([]))
                .await?;
            Ok(res["value"].as_str().unwrap_or("").to_string())
        })
        .await
    }

    /// Return the element's `outerHTML` (serialized element + children).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # let tab = browser.main_tab();
    /// let h1 = tab.find().css("h1").one().await?;
    /// assert!(h1.outer_html().await?.starts_with("<h1"));
    /// # Ok(()) }
    /// ```
    pub async fn outer_html(&self) -> Result<String> {
        self.with_refresh(|| async move {
            let res = self
                .call_on("function(){ return this.outerHTML; }", json!([]))
                .await?;
            Ok(res["value"].as_str().unwrap_or("").to_string())
        })
        .await
    }

    /// Return the viewport-relative bounding box, or `None` when absent.
    ///
    /// `None` typically means the element has no box (e.g. `display: none`)
    /// — Chrome reports this as `-32000 "Could not compute box model"` which
    /// is mapped to `None` rather than bubbling.
    ///
    /// Coordinates come from `DOM.getBoxModel`'s `content` quad (clock-wise
    /// starting top-left); `(width, height)` come from the top-level fields
    /// of the box-model response.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # let tab = browser.main_tab();
    /// let btn = tab.find().css("button").one().await?;
    /// if let Some(bbox) = btn.bounding_box().await? {
    ///     println!("button at ({}, {}) size {}x{}", bbox.x, bbox.y, bbox.width, bbox.height);
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn bounding_box(&self) -> Result<Option<BoundingBox>> {
        self.with_refresh(|| async move {
            let backend_node_id = self.backend_node_id_cloned().await?;
            let res = self
                .inner
                .tab
                .call(
                    "DOM.getBoxModel",
                    json!({ "backendNodeId": backend_node_id }),
                )
                .await;
            let res = match res {
                Ok(v) => v,
                // No box (display: none, detached, etc.) → None.
                Err(ZendriverError::Cdp { ref message, .. })
                    if message.contains("Could not compute box model") =>
                {
                    return Ok(None);
                }
                Err(e) => return Err(e),
            };
            let model = match res.get("model") {
                Some(m) => m,
                None => return Ok(None),
            };
            let content = match model.get("content").and_then(|v| v.as_array()) {
                Some(c) if c.len() >= 2 => c,
                _ => return Ok(None),
            };
            let x = content[0].as_f64().unwrap_or(0.0);
            let y = content[1].as_f64().unwrap_or(0.0);
            let width = model.get("width").and_then(|v| v.as_f64()).unwrap_or(0.0);
            let height = model.get("height").and_then(|v| v.as_f64()).unwrap_or(0.0);
            Ok(Some(BoundingBox {
                x,
                y,
                width,
                height,
            }))
        })
        .await
    }

    /// Return the page-absolute bounding box, or `None` when absent.
    ///
    /// Combines the viewport-relative [`Element::bounding_box`] with the
    /// page scroll offset (`window.scrollX` / `scrollY`), so the resulting
    /// [`PageBox`] can yield document-relative coordinates that stay stable
    /// as the page scrolls — via [`PageBox::abs_origin`] (top-left) and
    /// [`PageBox::abs_center`] (center).
    ///
    /// Ports nodriver's `Position.abs_x` / `abs_y` (element.py:504), the
    /// element center offset by the scroll position. `None` has the same
    /// meaning as in [`Element::bounding_box`] — the node has no box.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # let tab = browser.main_tab();
    /// let btn = tab.find().css("button").one().await?;
    /// if let Some(page) = btn.bounding_box_page().await? {
    ///     let (ax, ay) = page.abs_center();
    ///     println!("button center is at page ({ax}, {ay})");
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn bounding_box_page(&self) -> Result<Option<PageBox>> {
        self.with_refresh(|| async move {
            let Some(viewport) = self.bounding_box().await? else {
                return Ok(None);
            };
            // One round-trip for both scroll offsets. `pageXOffset` /
            // `pageYOffset` are the spec-stable aliases of `scrollX` /
            // `scrollY`.
            let res = self
                .call_on_main(
                    "function(){ return { x: window.scrollX, y: window.scrollY }; }",
                    json!([]),
                )
                .await?;
            let scroll = res.get("value").cloned().unwrap_or(Value::Null);
            let scroll_x = scroll.get("x").and_then(Value::as_f64).unwrap_or(0.0);
            let scroll_y = scroll.get("y").and_then(Value::as_f64).unwrap_or(0.0);
            Ok(Some(PageBox {
                viewport,
                scroll_x,
                scroll_y,
            }))
        })
        .await
    }

    /// Returns `true` iff the element is rendered + visible.
    ///
    /// Attached to the document, has a positive bounding box, and is not
    /// hidden via `display`, `visibility`, or `opacity: 0`. Uses the same
    /// internal visibility predicate that powers the actionability gate.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # let tab = browser.main_tab();
    /// let modal = tab.find().css(".modal").one().await?;
    /// if !modal.is_visible().await? {
    ///     println!("modal is hidden");
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn is_visible(&self) -> Result<bool> {
        self.with_refresh(|| async move { actionability::check_visible(self).await })
            .await
    }

    /// Returns `true` iff the element is not disabled.
    ///
    /// Native `el.disabled` is false-ish AND `aria-disabled` is not
    /// `'true'`. Non-form elements are considered enabled.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # let tab = browser.main_tab();
    /// let submit = tab.find().css("button[type=submit]").one().await?;
    /// if submit.is_enabled().await? {
    ///     submit.click().await?;
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn is_enabled(&self) -> Result<bool> {
        self.with_refresh(|| async move { actionability::check_enabled(self).await })
            .await
    }
}

#[cfg(test)]
#[allow(clippy::panic, clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::tab::Tab;
    use zendriver_transport::SessionHandle;
    use zendriver_transport::testing::MockConnection;

    #[tokio::test]
    async fn attr_returns_some_when_attribute_present() {
        let (mut mock, conn) = MockConnection::pair();
        let sess = SessionHandle::new(conn.clone(), "S1");
        let tab = Tab::new_for_test(sess);
        let el = Element::from_jsret(tab, 1, "R1".to_string());

        let fut = tokio::spawn({
            let e = el.clone();
            async move { e.attr("href").await }
        });

        let id = mock.expect_cmd("Runtime.callFunctionOn").await;
        let sent = mock.last_sent();
        assert_eq!(sent["params"]["objectId"], "R1");
        assert!(
            sent["params"]["functionDeclaration"]
                .as_str()
                .unwrap()
                .contains("getAttribute")
        );
        assert_eq!(sent["params"]["arguments"][0]["value"], "href");
        mock.reply(
            id,
            json!({ "result": { "value": "/login", "type": "string" } }),
        )
        .await;

        let got = fut.await.unwrap().unwrap();
        assert_eq!(got, Some("/login".to_string()));
        conn.shutdown();
    }

    #[tokio::test]
    async fn attrs_returns_hashmap_of_all_attributes() {
        let (mut mock, conn) = MockConnection::pair();
        let sess = SessionHandle::new(conn.clone(), "S1");
        let tab = Tab::new_for_test(sess);
        let el = Element::from_jsret(tab, 1, "R1".to_string());

        let fut = tokio::spawn({
            let e = el.clone();
            async move { e.attrs().await }
        });

        let id = mock.expect_cmd("Runtime.callFunctionOn").await;
        let sent = mock.last_sent();
        assert!(
            sent["params"]["functionDeclaration"]
                .as_str()
                .unwrap()
                .contains("attributes")
        );
        mock.reply(
            id,
            json!({
                "result": {
                    "value": { "id": "btn", "class": "primary", "data-x": "42" },
                    "type": "object"
                }
            }),
        )
        .await;

        let map = fut.await.unwrap().unwrap();
        assert_eq!(map.get("id").map(String::as_str), Some("btn"));
        assert_eq!(map.get("class").map(String::as_str), Some("primary"));
        assert_eq!(map.get("data-x").map(String::as_str), Some("42"));
        assert_eq!(map.len(), 3);
        conn.shutdown();
    }

    #[tokio::test]
    async fn bounding_box_parses_dom_get_box_model_content_quad() {
        let (mut mock, conn) = MockConnection::pair();
        let sess = SessionHandle::new(conn.clone(), "S1");
        let tab = Tab::new_for_test(sess);
        let el = Element::from_jsret(tab, 42, "R1".to_string());

        let fut = tokio::spawn({
            let e = el.clone();
            async move { e.bounding_box().await }
        });

        let id = mock.expect_cmd("DOM.getBoxModel").await;
        let sent = mock.last_sent();
        assert_eq!(sent["params"]["backendNodeId"], 42);
        mock.reply(
            id,
            json!({
                "model": {
                    // Quad: top-left (10,20), top-right (110,20),
                    // bottom-right (110,70), bottom-left (10,70).
                    "content": [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0],
                    "padding": [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0],
                    "border":  [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0],
                    "margin":  [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0],
                    "width":  100,
                    "height": 50
                }
            }),
        )
        .await;

        let bbox = fut.await.unwrap().unwrap().expect("should be Some");
        assert!((bbox.x - 10.0).abs() < 1e-9);
        assert!((bbox.y - 20.0).abs() < 1e-9);
        assert!((bbox.width - 100.0).abs() < 1e-9);
        assert!((bbox.height - 50.0).abs() < 1e-9);
        conn.shutdown();
    }

    #[tokio::test]
    async fn bounding_box_page_adds_scroll_offsets_to_viewport_box() {
        let (mut mock, conn) = MockConnection::pair();
        let sess = SessionHandle::new(conn.clone(), "S1");
        let tab = Tab::new_for_test(sess);
        let el = Element::from_jsret(tab, 42, "R1".to_string());

        let fut = tokio::spawn({
            let e = el.clone();
            async move { e.bounding_box_page().await }
        });

        // Step 1: bounding_box → DOM.getBoxModel. Box top-left (10,20), 100x50.
        let id = mock.expect_cmd("DOM.getBoxModel").await;
        assert_eq!(mock.last_sent()["params"]["backendNodeId"], 42);
        mock.reply(
            id,
            json!({
                "model": {
                    "content": [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0],
                    "padding": [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0],
                    "border":  [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0],
                    "margin":  [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0],
                    "width":  100,
                    "height": 50
                }
            }),
        )
        .await;

        // Step 2: scroll offsets via Runtime.callFunctionOn (window.scrollX/Y).
        let id = mock.expect_cmd("Runtime.callFunctionOn").await;
        assert!(
            mock.last_sent()["params"]["functionDeclaration"]
                .as_str()
                .unwrap()
                .contains("scrollX")
        );
        mock.reply(
            id,
            json!({ "result": { "value": { "x": 1000.0, "y": 500.0 }, "type": "object" } }),
        )
        .await;

        let page = fut.await.unwrap().unwrap().expect("should be Some");
        // Viewport box is unchanged.
        assert!((page.viewport.x - 10.0).abs() < 1e-9);
        assert!((page.viewport.y - 20.0).abs() < 1e-9);
        assert!((page.scroll_x - 1000.0).abs() < 1e-9);
        assert!((page.scroll_y - 500.0).abs() < 1e-9);
        // Page-absolute origin = viewport origin + scroll.
        let (ax, ay) = page.abs_origin();
        assert!((ax - 1010.0).abs() < 1e-9);
        assert!((ay - 520.0).abs() < 1e-9);
        // Page-absolute center = origin + half-size + scroll (nodriver abs_x/y).
        let (cx, cy) = page.abs_center();
        assert!((cx - 1060.0).abs() < 1e-9); // 10 + 50 + 1000
        assert!((cy - 545.0).abs() < 1e-9); // 20 + 25 + 500
        conn.shutdown();
    }
}