Skip to content

Commit

Permalink
Storage cookie functions (#233)
Browse files Browse the repository at this point in the history
* Added Storage cookie functions

See: https://chromedevtools.github.io/devtools-protocol/tot/Storage/

* Added Storage cookie example

* rustfmt

---------

Co-authored-by: Matthias Seitz <[email protected]>
  • Loading branch information
Nathan-Mossaad and mattsse authored Aug 12, 2024
1 parent fc7b476 commit 6968e92
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 1 deletion.
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ required-features = ["tokio-runtime"]
name = "iframe-workaround"
required-features = ["tokio-runtime", "tokio"]

[[example]]
name = "storage-cookie"
required-features = ["tokio-runtime"]


[[example]]
name = "httpfuture"
Expand Down
48 changes: 48 additions & 0 deletions examples/storage-cookie.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
use futures::StreamExt;

use chromiumoxide::browser::Browser;
use chromiumoxide::browser::BrowserConfig;
use chromiumoxide::cdp::browser_protocol::network::CookieParam;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing_subscriber::fmt::init();

let (mut browser, mut handler) =
Browser::launch(BrowserConfig::builder().with_head().build()?).await?;
let _ = tokio::spawn(async move { while let Some(_) = handler.next().await {} });

let _ = browser.new_page("https://setcookie.net/").await?;
let example_cookie = CookieParam::builder()
.domain(".setcookie.net")
.name("set_from_chromiumoxide")
.value("Test Value")
.path("/")
.build()?;

println!("\x1b[32mType 'c' to clear all cookies, 's' to set a cookie, 'q' to quit the browser\x1b[0m");
loop {
// Read Cookies
println!("All Browser cookies: {:?}", browser.get_cookies().await?);

let mut input = String::new();
std::io::stdin().read_line(&mut input)?;

if input.trim() == "c" {
// Clear Cookies
browser.clear_cookies().await?;
}
if input.trim() == "s" {
// Set Cookies
browser.set_cookies(vec![example_cookie.clone()]).await?;
}
if input.trim() == "q" {
break;
}
}

browser.close().await?;
browser.wait().await?;

Ok(())
}
31 changes: 31 additions & 0 deletions src/browser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ use futures::channel::oneshot::channel as oneshot_channel;
use futures::select;
use futures::SinkExt;

use chromiumoxide_cdp::cdp::browser_protocol::network::{Cookie, CookieParam};
use chromiumoxide_cdp::cdp::browser_protocol::storage::{
ClearCookiesParams, GetCookiesParams, SetCookiesParams,
};
use chromiumoxide_cdp::cdp::browser_protocol::target::{
CreateBrowserContextParams, CreateTargetParams, DisposeBrowserContextParams, TargetId,
TargetInfo,
Expand Down Expand Up @@ -480,6 +484,33 @@ impl Browser {

Ok(())
}

/// Clears cookies.
pub async fn clear_cookies(&self) -> Result<()> {
self.execute(ClearCookiesParams::default()).await?;
Ok(())
}

/// Returns all browser cookies.
pub async fn get_cookies(&self) -> Result<Vec<Cookie>> {
Ok(self
.execute(GetCookiesParams::default())
.await?
.result
.cookies)
}

/// Sets given cookies.
pub async fn set_cookies(&self, mut cookies: Vec<CookieParam>) -> Result<&Self> {
for cookie in &mut cookies {
if let Some(url) = cookie.url.as_ref() {
crate::page::validate_cookie_url(url)?;
}
}

self.execute(SetCookiesParams::new(cookies)).await?;
Ok(self)
}
}

impl Drop for Browser {
Expand Down
2 changes: 1 addition & 1 deletion src/page.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1240,7 +1240,7 @@ impl From<Arc<PageInner>> for Page {
}
}

fn validate_cookie_url(url: &str) -> Result<()> {
pub(crate) fn validate_cookie_url(url: &str) -> Result<()> {
if url.starts_with("data:") {
Err(CdpError::msg("Data URL page can not have cookie"))
} else if url == "about:blank" {
Expand Down

0 comments on commit 6968e92

Please sign in to comment.