Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Storage cookie functions #233

Merged
merged 4 commits into from
Aug 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading