browsing 0.1.7

Browser automation: navigate, click, extract, screenshot. Standalone browser control via CDP.
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
//! Page operations for browser automation

use crate::actor::{Element, Mouse, MouseButton, get_key_info};
use crate::browser::cdp::CdpClient;
use crate::error::{BrowsingError, Result};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::sync::Arc;

/// A found element within a Shadow DOM
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShadowElementInfo {
    /// Element tag name
    pub tag_name: String,
    /// Element text content
    pub text: Option<String>,
    /// Element id attribute
    pub id: Option<String>,
    /// Element class attribute
    pub class: Option<String>,
    /// Element name attribute
    pub name: Option<String>,
    /// Whether the element is visible
    pub visible: bool,
    /// Bounding box coordinates {x, y, width, height}
    pub bounding_box: Option<serde_json::Value>,
}

/// Page operations (tab or iframe)
pub struct Page {
    client: Arc<CdpClient>,
    session_id: Arc<str>,
    mouse: Option<Mouse>,
}

impl Page {
    /// Creates a new Page instance with the given CDP client and session ID
    pub fn new(client: Arc<CdpClient>, session_id: impl Into<Arc<str>>) -> Self {
        Self {
            client,
            session_id: session_id.into(),
            mouse: None,
        }
    }

    /// Get the mouse interface for this page
    pub async fn mouse(&mut self) -> &mut Mouse {
        if self.mouse.is_none() {
            self.mouse = Some(Mouse::new(
                Arc::clone(&self.client),
                self.session_id.clone(),
            ));
        }
        self.mouse.as_mut().unwrap()
    }

    /// Reload the page
    pub async fn reload(&self) -> Result<()> {
        self.client.send_command("Page.reload", json!({})).await?;
        Ok(())
    }

    /// Go back in browser history
    pub async fn go_back(&self) -> Result<()> {
        self.evaluate("history.back()").await?;
        Ok(())
    }

    /// Go forward in browser history
    pub async fn go_forward(&self) -> Result<()> {
        self.evaluate("history.forward()").await?;
        Ok(())
    }

    /// Navigate to URL
    pub async fn goto(&self, url: &str) -> Result<()> {
        let params = json!({
            "url": url
        });
        self.client.send_command("Page.navigate", params).await?;
        Ok(())
    }

    /// Get an element by its backend node ID
    pub async fn get_element(&self, backend_node_id: u32) -> Element {
        Element::new(
            Arc::clone(&self.client),
            self.session_id.clone(),
            backend_node_id,
        )
    }

    /// Get elements by CSS selector
    pub async fn get_elements_by_css_selector(&self, selector: &str) -> Result<Vec<Element>> {
        // First, get document node
        let document_result = self
            .client
            .send_command("DOM.getDocument", json!({ "depth": 0 }))
            .await?;

        let root_node_id = document_result
            .get("root")
            .and_then(|v| v.get("nodeId"))
            .and_then(|v| v.as_u64())
            .ok_or_else(|| BrowsingError::Dom("No root node found".to_string()))?;

        // Query selector
        let query_params = json!({
            "nodeId": root_node_id,
            "selector": selector
        });
        let query_result = self
            .client
            .send_command("DOM.querySelectorAll", query_params)
            .await?;

        let node_ids = query_result
            .get("nodeIds")
            .and_then(|v| v.as_array())
            .ok_or_else(|| BrowsingError::Dom("No nodeIds in query result".to_string()))?;

        let mut elements = Vec::new();
        for node_id_value in node_ids {
            if let Some(node_id) = node_id_value.as_u64() {
                // Get backend node ID
                let describe_params = json!({
                    "nodeId": node_id
                });
                if let Ok(describe_result) = self
                    .client
                    .send_command("DOM.describeNode", describe_params)
                    .await
                    && let Some(backend_node_id) = describe_result
                        .get("node")
                        .and_then(|v| v.get("backendNodeId"))
                        .and_then(|v| v.as_u64())
                    {
                        elements.push(Element::new(
                            Arc::clone(&self.client),
                            self.session_id.clone(),
                            backend_node_id as u32,
                        ));
                    }
            }
        }

        Ok(elements)
    }

    /// Execute JavaScript in the page
    pub async fn evaluate(&self, expression: &str) -> Result<String> {
        let params = json!({
            "expression": expression,
            "returnByValue": true,
            "awaitPromise": true
        });
        let result = self.client.send_command("Runtime.evaluate", params).await?;

        if let Some(exception) = result.get("exceptionDetails") {
            return Err(BrowsingError::Dom(format!(
                "JavaScript evaluation failed: {exception}"
            )));
        }

        let value = result.get("result").and_then(|v| v.get("value"));

        match value {
            Some(serde_json::Value::String(s)) => Ok(s.clone()),
            Some(v) => Ok(serde_json::to_string(v)?),
            None => Ok(String::new()),
        }
    }

    /// Take a screenshot
    pub async fn screenshot(&self, format: Option<&str>, quality: Option<u32>) -> Result<String> {
        self.screenshot_with_options(format, quality, false, None)
            .await
    }

    /// Take a screenshot with additional options
    pub async fn screenshot_with_options(
        &self,
        format: Option<&str>,
        quality: Option<u32>,
        full_page: bool,
        clip: Option<(f64, f64, f64, f64)>,
    ) -> Result<String> {
        let format = format.unwrap_or("png");
        let mut params = json!({
            "format": format,
            "captureBeyondViewport": full_page
        });

        if format == "jpeg"
            && let Some(q) = quality {
                params["quality"] = json!(q);
            }

        if let Some((x, y, width, height)) = clip {
            params["clip"] = json!({
                "x": x,
                "y": y,
                "width": width,
                "height": height,
                "scale": 1.0
            });
        }

        let result = self
            .client
            .send_command_with_session("Page.captureScreenshot", params, Some(&self.session_id))
            .await?;

        let data = result
            .get("data")
            .and_then(|v| v.as_str())
            .ok_or_else(|| BrowsingError::Browser("No screenshot data".to_string()))?;

        Ok(data.to_string())
    }

    /// Press a key on the page (supports key combinations like "Control+A")
    pub async fn press(&self, key: &str) -> Result<()> {
        // Handle key combinations like "Control+A"
        if key.contains('+') {
            let parts: Vec<&str> = key.split('+').collect();
            let modifiers = &parts[..parts.len() - 1];
            let main_key = parts.last().unwrap();

            // Calculate modifier bitmask
            let mut modifier_value = 0u32;
            let modifier_map: std::collections::HashMap<&str, u32> =
                [("Alt", 1), ("Control", 2), ("Meta", 4), ("Shift", 8)]
                    .iter()
                    .cloned()
                    .collect();

            for mod_str in modifiers {
                if let Some(&val) = modifier_map.get(mod_str) {
                    modifier_value |= val;
                }
            }

            // Press modifier keys
            for mod_str in modifiers {
                let (code, vk_code) = get_key_info(mod_str);
                let mut params = json!({
                    "type": "keyDown",
                    "key": mod_str,
                    "code": code
                });
                if let Some(vk) = vk_code {
                    params["windowsVirtualKeyCode"] = json!(vk);
                }
                self.client
                    .send_command("Input.dispatchKeyEvent", params)
                    .await?;
            }

            // Press main key with modifiers
            let (main_code, main_vk_code) = get_key_info(main_key);
            let mut main_down_params = json!({
                "type": "keyDown",
                "key": main_key,
                "code": main_code,
                "modifiers": modifier_value
            });
            if let Some(vk) = main_vk_code {
                main_down_params["windowsVirtualKeyCode"] = json!(vk);
            }
            self.client
                .send_command("Input.dispatchKeyEvent", main_down_params)
                .await?;

            let mut main_up_params = json!({
                "type": "keyUp",
                "key": main_key,
                "code": main_code,
                "modifiers": modifier_value
            });
            if let Some(vk) = main_vk_code {
                main_up_params["windowsVirtualKeyCode"] = json!(vk);
            }
            self.client
                .send_command("Input.dispatchKeyEvent", main_up_params)
                .await?;

            // Release modifier keys
            for mod_str in modifiers.iter().rev() {
                let (code, vk_code) = get_key_info(mod_str);
                let mut params = json!({
                    "type": "keyUp",
                    "key": mod_str,
                    "code": code
                });
                if let Some(vk) = vk_code {
                    params["windowsVirtualKeyCode"] = json!(vk);
                }
                self.client
                    .send_command("Input.dispatchKeyEvent", params)
                    .await?;
            }
        } else {
            // Simple key press
            let (code, vk_code) = get_key_info(key);
            let mut key_down_params = json!({
                "type": "keyDown",
                "key": key,
                "code": code
            });
            if let Some(vk) = vk_code {
                key_down_params["windowsVirtualKeyCode"] = json!(vk);
            }
            self.client
                .send_command("Input.dispatchKeyEvent", key_down_params)
                .await?;

            let mut key_up_params = json!({
                "type": "keyUp",
                "key": key,
                "code": code
            });
            if let Some(vk) = vk_code {
                key_up_params["windowsVirtualKeyCode"] = json!(vk);
            }
            self.client
                .send_command("Input.dispatchKeyEvent", key_up_params)
                .await?;
        }

        Ok(())
    }

    /// Verify that a backend node ID is still valid in the current DOM.
    /// Uses CDP `DOM.describeNode` with `backendNodeId`; returns true if the node exists.
    pub async fn verify_backend_node(&self, backend_node_id: u32) -> bool {
        let params = serde_json::json!({
            "backendNodeId": backend_node_id,
            "depth": 0
        });
        self.client
            .send_command_with_session("DOM.describeNode", params, Some(&self.session_id))
            .await
            .is_ok()
    }

    /// Set viewport size
    pub async fn set_viewport_size(&self, width: u32, height: u32) -> Result<()> {
        let params = json!({
            "width": width,
            "height": height,
            "deviceScaleFactor": 1.0,
            "mobile": false
        });
        self.client
            .send_command("Emulation.setDeviceMetricsOverride", params)
            .await?;
        Ok(())
    }

    /// Query a single element inside a Shadow DOM by host selector and inner CSS selector.
    /// Returns `None` if no matching element is found.
    pub async fn query_shadow_dom(
        &self,
        host_selector: &str,
        inner_selector: &str,
    ) -> Result<Option<ShadowElementInfo>> {
        let script = format!(
            r#"(function() {{
                var host = document.querySelector({});
                if (!host || !host.shadowRoot) return null;
                var el = host.shadowRoot.querySelector({});
                if (!el) return null;
                var rect = el.getBoundingClientRect();
                return JSON.stringify({{
                    tag_name: el.tagName.toLowerCase(),
                    text: el.textContent || '',
                    id: el.id || null,
                    class: el.className || null,
                    name: el.getAttribute('name') || null,
                    visible: !!(el.offsetParent || el.getClientRects().length > 0),
                    bounding_box: {{ x: rect.x, y: rect.y, width: rect.width, height: rect.height }}
                }});
            }})()"#,
            serde_json::json!(host_selector),
            serde_json::json!(inner_selector)
        );

        let result = self.evaluate(&script).await?;
        if result.is_empty() || result == "null" {
            return Ok(None);
        }
        let info: ShadowElementInfo = serde_json::from_str(&result)
            .map_err(|e| BrowsingError::Dom(format!("Shadow DOM parse error: {e}")))?;
        Ok(Some(info))
    }

    /// Query all matching elements inside a Shadow DOM.
    pub async fn query_all_shadow_dom(
        &self,
        host_selector: &str,
        inner_selector: &str,
    ) -> Result<Vec<ShadowElementInfo>> {
        let script = format!(
            r#"(function() {{
                var host = document.querySelector({});
                if (!host || !host.shadowRoot) return '[]';
                var els = host.shadowRoot.querySelectorAll({});
                var result = [];
                for (var i = 0; i < els.length; i++) {{
                    var el = els[i];
                    var rect = el.getBoundingClientRect();
                    result.push({{
                        tag_name: el.tagName.toLowerCase(),
                        text: el.textContent || '',
                        id: el.id || null,
                        class: el.className || null,
                        name: el.getAttribute('name') || null,
                        visible: !!(el.offsetParent || el.getClientRects().length > 0),
                        bounding_box: {{ x: rect.x, y: rect.y, width: rect.width, height: rect.height }}
                    }});
                }}
                return JSON.stringify(result);
            }})()"#,
            serde_json::json!(host_selector),
            serde_json::json!(inner_selector)
        );

        let result = self.evaluate(&script).await?;
        if result.is_empty() {
            return Ok(Vec::new());
        }
        let infos: Vec<ShadowElementInfo> = serde_json::from_str(&result)
            .map_err(|e| BrowsingError::Dom(format!("Shadow DOM parse error: {e}")))?;
        Ok(infos)
    }

    /// Check whether an element has an open Shadow Root.
    pub async fn has_shadow_root(&self, selector: &str) -> Result<bool> {
        let script = format!(
            r#"(function() {{
                var el = document.querySelector({});
                return !!(el && el.shadowRoot);
            }})()"#,
            serde_json::json!(selector)
        );
        let result = self.evaluate(&script).await?;
        Ok(result.trim() == "true")
    }

    /// Get a list of CSS selectors for all elements with open Shadow Roots on the page.
    pub async fn get_shadow_host_elements(&self) -> Result<Vec<String>> {
        let script = r#"(function() {
            var hosts = [];
            var all = document.querySelectorAll('*');
            for (var i = 0; i < all.length; i++) {
                if (all[i].shadowRoot) {
                    var tag = all[i].tagName.toLowerCase();
                    var id = all[i].id ? '#' + all[i].id : '';
                    var cls = all[i].className ? '.' + all[i].className.split(' ').join('.') : '';
                    hosts.push(tag + id + cls);
                }
            }
            return JSON.stringify(hosts);
        })()"#;
        let result = self.evaluate(script).await?;
        let hosts: Vec<String> = serde_json::from_str(&result).unwrap_or_default();
        Ok(hosts)
    }

    /// Drag and drop from one coordinate to another.
    pub async fn drag_and_drop(
        &self,
        start_x: f64,
        start_y: f64,
        end_x: f64,
        end_y: f64,
    ) -> Result<()> {
        let mouse = Mouse::new(Arc::clone(&self.client), self.session_id.clone());
        mouse.drag(start_x, start_y, end_x, end_y, MouseButton::Left).await
    }

    /// Drag and drop an element by selector to target coordinates.
    pub async fn drag_element_to(
        &self,
        selector: &str,
        end_x: f64,
        end_y: f64,
    ) -> Result<()> {
        let script = format!(
            r#"(function() {{
                var el = document.querySelector({});
                if (!el) return null;
                var rect = el.getBoundingClientRect();
                return JSON.stringify({{ x: rect.x + rect.width/2, y: rect.y + rect.height/2 }});
            }})()"#,
            serde_json::json!(selector)
        );
        let result = self.evaluate(&script).await?;
        if result.is_empty() || result == "null" {
            return Err(BrowsingError::Dom(format!("Element not found: {selector}")));
        }
        let coords: serde_json::Value = serde_json::from_str(&result)
            .map_err(|e| BrowsingError::Dom(format!("Drag parse error: {e}")))?;
        let start_x = coords.get("x").and_then(|v| v.as_f64()).unwrap_or(0.0);
        let start_y = coords.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0);
        self.drag_and_drop(start_x, start_y, end_x, end_y).await
    }
}