Skip to content

Commit

Permalink
feat: add WebView::cookies and WebView::cookies_for_url (#1394)
Browse files Browse the repository at this point in the history
* feat: add `WebView::cookies` and `WebView::cookies_for_url`

closes #518
ref: tauri-apps/tauri#11330

* cookies -> getCookies in android

* fix macos build

* fix gtk blocking

* document why we don't use wait_for_async_operation

* change file

* implement cookies_for_url on macOS

* fmt

* fix macos impl

* actually use interval

* make it faster

* remove matching on path

* Apply suggestions from code review

Co-authored-by: Lucas Fernandes Nogueira <[email protected]>

* Apply suggestions from code review

---------

Co-authored-by: Lucas Nogueira <[email protected]>
  • Loading branch information
amrbashir and lucasfernog authored Oct 21, 2024
1 parent 6c1f0da commit c1b26b9
Show file tree
Hide file tree
Showing 12 changed files with 537 additions and 126 deletions.
5 changes: 5 additions & 0 deletions .changes/cookies-api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"wry": "patch"
---

Add `WebView::cookies` and `WebView::cookies_for_url` APIs.
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ thiserror = "1.0"
http = "1.1"
raw-window-handle = { version = "0.6", features = ["std"] }
dpi = "0.1"
cookie = "0.18"

[target."cfg(any(target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\"))".dependencies]
javascriptcore-rs = { version = "=1.1.2", features = [
Expand Down Expand Up @@ -93,6 +94,7 @@ features = [
]

[target."cfg(any(target_os = \"ios\", target_os = \"macos\"))".dependencies]
url = "2.5"
block2 = "0.5"
objc2 = { version = "0.5", features = ["exception"] }
objc2-web-kit = { version = "0.2.0", features = [
Expand All @@ -119,6 +121,7 @@ objc2-web-kit = { version = "0.2.0", features = [
"WKWebpagePreferences",
"WKNavigationResponse",
"WKUserScript",
"WKHTTPCookieStore",
] }
objc2-foundation = { version = "0.2.0", features = [
"NSURLRequest",
Expand All @@ -137,6 +140,7 @@ objc2-foundation = { version = "0.2.0", features = [
"NSProcessInfo",
"NSValue",
"NSRange",
"NSRunLoop",
] }

[target."cfg(target_os = \"ios\")".dependencies]
Expand Down
40 changes: 0 additions & 40 deletions examples/custom_protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,46 +19,6 @@ fn main() -> wry::Result<()> {
let window = WindowBuilder::new().build(&event_loop).unwrap();

let builder = WebViewBuilder::new()
.with_id("id2")
.with_custom_protocol(
"wry".into(),
move |_webview_id, request| match get_wry_response(request) {
Ok(r) => r.map(Into::into),
Err(e) => http::Response::builder()
.header(CONTENT_TYPE, "text/plain")
.status(500)
.body(e.to_string().as_bytes().to_vec())
.unwrap()
.map(Into::into),
},
)
// tell the webview to load the custom protocol
.with_url("wry://localhost");

#[cfg(any(
target_os = "windows",
target_os = "macos",
target_os = "ios",
target_os = "android"
))]
let _webview = builder.build(&window)?;
#[cfg(not(any(
target_os = "windows",
target_os = "macos",
target_os = "ios",
target_os = "android"
)))]
let _webview = {
use tao::platform::unix::WindowExtUnix;
use wry::WebViewBuilderExtUnix;
let vbox = window.default_vbox().unwrap();
builder.build_gtk(vbox)?
};

let window = WindowBuilder::new().build(&event_loop).unwrap();

let builder = WebViewBuilder::new()
.with_id("id1")
.with_custom_protocol(
"wry".into(),
move |_webview_id, request| match get_wry_response(request) {
Expand Down
2 changes: 1 addition & 1 deletion examples/simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ fn main() -> wry::Result<()> {
..
} = event
{
*control_flow = ControlFlow::Exit
*control_flow = ControlFlow::Exit;
}
});
}
5 changes: 5 additions & 0 deletions src/android/kotlin/RustWebView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@ class RustWebView(context: Context, val initScripts: Array<String>, val id: Stri
settings.userAgentString = ua
}

fun getCookies(url: String): String {
val cookieManager = CookieManager.getInstance()
return cookieManager.getCookie(url)
}

private external fun shouldOverride(url: String): Boolean
private external fun onEval(id: Int, result: String)

Expand Down
52 changes: 32 additions & 20 deletions src/android/main_pipe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use jni::{
JNIEnv,
};
use once_cell::sync::Lazy;
use std::{os::unix::prelude::*, sync::atomic::Ordering};
use std::{os::unix::prelude::*, str::FromStr, sync::atomic::Ordering};

use super::{find_class, EvalCallback, EVAL_CALLBACKS, EVAL_ID_GENERATOR, PACKAGE};

Expand Down Expand Up @@ -267,24 +267,6 @@ impl<'a> MainPipe<'a> {
Err(e) => tx.send(Err(e.into())).unwrap(),
}
}
WebViewMessage::GetId(tx) => {
if let Some(webview) = &self.webview {
let url = self
.env
.call_method(webview.as_obj(), "getUrl", "()Ljava/lang/String;", &[])
.and_then(|v| v.l())
.and_then(|s| {
let s = JString::from(s);
self
.env
.get_string(&s)
.map(|v| v.to_string_lossy().to_string())
})
.unwrap_or_default();

tx.send(url).unwrap()
}
}
WebViewMessage::GetUrl(tx) => {
if let Some(webview) = &self.webview {
let url = self
Expand Down Expand Up @@ -329,6 +311,36 @@ impl<'a> MainPipe<'a> {
load_html(&mut self.env, webview.as_obj(), &html)?;
}
}
WebViewMessage::GetCookies(tx, url) => {
if let Some(webview) = &self.webview {
let url = self.env.new_string(url)?;
let cookies = self
.env
.call_method(
webview,
"getCookies",
"(Ljava/lang/String;)Ljava/lang/String;",
&[(&url).into()],
)
.and_then(|v| v.l())
.and_then(|s| {
let s = JString::from(s);
self
.env
.get_string(&s)
.map(|v| v.to_string_lossy().to_string())
})
.unwrap_or_default();

tx.send(
cookies
.split("; ")
.flat_map(|c| cookie::Cookie::parse(c.to_string()))
.collect(),
)
.unwrap();
}
}
}
}
Ok(())
Expand Down Expand Up @@ -395,8 +407,8 @@ pub(crate) enum WebViewMessage {
Eval(String, Option<EvalCallback>),
SetBackgroundColor(RGBA),
GetWebViewVersion(Sender<Result<String, Error>>),
GetId(Sender<String>),
GetUrl(Sender<String>),
GetCookies(Sender<Vec<cookie::Cookie<'static>>>, String),
Jni(Box<dyn FnOnce(&mut JNIEnv, &JObject, &JObject) + Send>),
LoadUrl(String, Option<http::HeaderMap>),
LoadHtml(String),
Expand Down
10 changes: 10 additions & 0 deletions src/android/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,16 @@ impl InnerWebView {
Ok(())
}

pub fn cookies_for_url(&self, url: &str) -> Result<Vec<cookie::Cookie<'static>>> {
let (tx, rx) = bounded(1);
MainPipe::send(WebViewMessage::GetCookies(tx, url.to_string()));
rx.recv().map_err(Into::into)
}

pub fn cookies(&self) -> Result<Vec<cookie::Cookie<'static>>> {
Ok(Vec::new())
}

pub fn bounds(&self) -> Result<crate::Rect> {
Ok(crate::Rect::default())
}
Expand Down
3 changes: 3 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,7 @@ pub enum Error {
DuplicateCustomProtocol(String),
#[error("Duplicate custom protocol registered on the same web context on Linux: {0}")]
ContextDuplicateCustomProtocol(String),
#[error(transparent)]
#[cfg(any(target_os = "macos", target_os = "ios"))]
UrlPrase(#[from] url::ParseError),
}
15 changes: 15 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@ use std::{borrow::Cow, collections::HashMap, path::PathBuf, rc::Rc};

use http::{Request, Response};

pub use cookie;
pub use dpi;
pub use error::*;
pub use http;
Expand Down Expand Up @@ -1517,6 +1518,20 @@ impl WebView {
self.webview.print()
}

/// Get a list of cookies for specific url.
pub fn cookies_for_url(&self, url: &str) -> Result<Vec<cookie::Cookie<'static>>> {
self.webview.cookies_for_url(url)
}

/// Get the list of cookies.
///
/// ## Platform-specific
///
/// - **Android**: Unsupported, always returns an empty [`Vec`].
pub fn cookies(&self) -> Result<Vec<cookie::Cookie<'static>>> {
self.webview.cookies()
}

/// Open the web inspector which is usually called dev tool.
///
/// ## Platform-specific
Expand Down
Loading

0 comments on commit c1b26b9

Please sign in to comment.