Skip to main content

browser_automation_cli/native/
cookies.rs

1#![allow(missing_docs)]
2use serde::{Deserialize, Serialize};
3use serde_json::{json, Value};
4
5use super::cdp::client::CdpClient;
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
8#[serde(rename_all = "camelCase")]
9pub struct Cookie {
10    pub name: String,
11    pub value: String,
12    pub domain: String,
13    pub path: String,
14    #[serde(default)]
15    pub expires: f64,
16    #[serde(default)]
17    pub size: i64,
18    #[serde(default)]
19    pub http_only: bool,
20    #[serde(default)]
21    pub secure: bool,
22    #[serde(default)]
23    pub session: bool,
24    #[serde(skip_serializing_if = "Option::is_none")]
25    pub same_site: Option<String>,
26}
27
28pub async fn get_all_cookies(client: &CdpClient, session_id: &str) -> Result<Vec<Cookie>, String> {
29    let result = client
30        .send_command_no_params("Network.getAllCookies", Some(session_id))
31        .await?;
32
33    let cookies: Vec<Cookie> = result
34        .get("cookies")
35        .and_then(|v| serde_json::from_value(v.clone()).ok())
36        .unwrap_or_default();
37
38    Ok(cookies)
39}
40
41pub async fn get_cookies(
42    client: &CdpClient,
43    session_id: &str,
44    urls: Option<Vec<String>>,
45) -> Result<Vec<Cookie>, String> {
46    let params = match urls {
47        Some(ref u) if !u.is_empty() => json!({ "urls": u }),
48        _ => json!({}),
49    };
50
51    let result = client
52        .send_command("Network.getCookies", Some(params), Some(session_id))
53        .await?;
54
55    let cookies: Vec<Cookie> = result
56        .get("cookies")
57        .and_then(|v| serde_json::from_value(v.clone()).ok())
58        .unwrap_or_default();
59
60    Ok(cookies)
61}
62
63pub async fn set_cookies(
64    client: &CdpClient,
65    session_id: &str,
66    cookies: Vec<Value>,
67    current_url: Option<&str>,
68) -> Result<(), String> {
69    let cookies: Vec<Value> = cookies
70        .into_iter()
71        .map(|mut c| {
72            // Auto-fill url if no domain/path/url provided
73            if c.get("url").is_none() && c.get("domain").is_none() && current_url.is_some() {
74                c.as_object_mut().map(|m| {
75                    m.insert(
76                        "url".to_string(),
77                        Value::String(current_url.unwrap().to_string()),
78                    )
79                });
80            }
81            c
82        })
83        .collect();
84
85    client
86        .send_command(
87            "Network.setCookies",
88            Some(json!({ "cookies": cookies })),
89            Some(session_id),
90        )
91        .await?;
92
93    Ok(())
94}
95
96pub async fn clear_cookies(client: &CdpClient, session_id: &str) -> Result<(), String> {
97    client
98        .send_command_no_params("Network.clearBrowserCookies", Some(session_id))
99        .await?;
100    Ok(())
101}