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

feat: on page load handler #980

Merged
merged 21 commits into from
Jul 23, 2023
Merged
Show file tree
Hide file tree
Changes from 16 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
6 changes: 6 additions & 0 deletions .changes/on-load-handler.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"wry": "minor"
---

Add `WebViewBuilder::with_on_page_loading_handler` for providing a callback when a new page starts to load.
Add `WebViewBuilder::with_on_page_loaded_handler` for providing a callback when a page load is complete.
30 changes: 28 additions & 2 deletions src/webview/android/binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ use tao::platform::android::ndk_glue::jni::{
};

use super::{
create_headers_map, ASSET_LOADER_DOMAIN, IPC, REQUEST_HANDLER, TITLE_CHANGE_HANDLER,
URL_LOADING_OVERRIDE, WITH_ASSET_LOADER,
create_headers_map, ASSET_LOADER_DOMAIN, IPC, ON_LOADED_HANDLER, ON_LOADING_HANDLER,
REQUEST_HANDLER, TITLE_CHANGE_HANDLER, URL_LOADING_OVERRIDE, WITH_ASSET_LOADER,
};

fn handle_request(env: JNIEnv, request: JObject) -> Result<jobject, JniError> {
Expand Down Expand Up @@ -205,3 +205,29 @@ pub unsafe fn assetLoaderDomain(env: JNIEnv, _: JClass) -> jstring {
env.new_string("wry.assets").unwrap().into_raw()
}
}

#[allow(non_snake_case)]
pub unsafe fn onPageLoading(env: JNIEnv, _: JClass, url: JString) {
match env.get_string(url) {
Ok(url) => {
let url = url.to_string_lossy().to_string();
if let Some(h) = ON_LOADING_HANDLER.get() {
(h.0)(url)
}
}
Err(e) => log::warn!("Failed to parse JString: {}", e),
}
}

#[allow(non_snake_case)]
pub unsafe fn onPageLoaded(env: JNIEnv, _: JClass, url: JString) {
match env.get_string(url) {
Ok(url) => {
let url = url.to_string_lossy().to_string();
if let Some(h) = ON_LOADED_HANDLER.get() {
(h.0)(url)
}
}
Err(e) => log::warn!("Failed to parse JString: {}", e),
}
}
11 changes: 11 additions & 0 deletions src/webview/android/kotlin/RustWebViewClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package {{package}}

import android.webkit.*
import android.content.Context
import android.graphics.Bitmap
import androidx.webkit.WebViewAssetLoader

class RustWebViewClient(context: Context): WebViewClient() {
Expand All @@ -32,6 +33,14 @@ class RustWebViewClient(context: Context): WebViewClient() {
return shouldOverride(request.url.toString())
}

override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?): Unit {
return onPageLoading(url)
}

override fun onPageFinished(view: WebView, url: String): Unit {
return onPageLoaded(url)
}


companion object {
init {
Expand All @@ -43,6 +52,8 @@ class RustWebViewClient(context: Context): WebViewClient() {
private external fun withAssetLoader(): Boolean
private external fun handleRequest(request: WebResourceRequest): WebResourceResponse?
private external fun shouldOverride(url: String): Boolean
private external fun onPageLoading(url: String)
private external fun onPageLoaded(url: String)

{{class-extension}}
}
42 changes: 42 additions & 0 deletions src/webview/android/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,20 @@ macro_rules! android_binding {
[JString],
jboolean
);
android_fn!(
$domain,
$package,
RustWebViewClient,
onPageLoading,
[JString]
);
android_fn!(
$domain,
$package,
RustWebViewClient,
onPageLoaded,
[JString]
);
android_fn!($domain, $package, Ipc, ipc, [JString]);
android_fn!(
$domain,
Expand All @@ -107,6 +121,8 @@ pub static TITLE_CHANGE_HANDLER: OnceCell<UnsafeTitleHandler> = OnceCell::new();
pub static WITH_ASSET_LOADER: OnceCell<bool> = OnceCell::new();
pub static ASSET_LOADER_DOMAIN: OnceCell<String> = OnceCell::new();
pub static URL_LOADING_OVERRIDE: OnceCell<UnsafeUrlLoadingOverride> = OnceCell::new();
pub static ON_LOADING_HANDLER: OnceCell<UnsafeOnPageLoadingHandler> = OnceCell::new();
pub static ON_LOADED_HANDLER: OnceCell<UnsafeOnPageLoadedHandler> = OnceCell::new();

pub struct UnsafeIpc(Box<dyn Fn(&Window, String)>, Rc<Window>);
impl UnsafeIpc {
Expand Down Expand Up @@ -146,6 +162,24 @@ impl UnsafeUrlLoadingOverride {
unsafe impl Send for UnsafeUrlLoadingOverride {}
unsafe impl Sync for UnsafeUrlLoadingOverride {}

pub struct UnsafeOnPageLoadingHandler(Box<dyn Fn(String)>);
impl UnsafeOnPageLoadingHandler {
pub fn new(f: Box<dyn Fn(String)>) -> Self {
Self(f)
}
}
unsafe impl Send for UnsafeOnPageLoadingHandler {}
unsafe impl Sync for UnsafeOnPageLoadingHandler {}

pub struct UnsafeOnPageLoadedHandler(Box<dyn Fn(String)>);
impl UnsafeOnPageLoadedHandler {
pub fn new(f: Box<dyn Fn(String)>) -> Self {
Self(f)
}
}
unsafe impl Send for UnsafeOnPageLoadedHandler {}
unsafe impl Sync for UnsafeOnPageLoadedHandler {}

pub unsafe fn setup(env: JNIEnv, looper: &ForeignLooper, activity: GlobalRef) {
// we must create the WebChromeClient here because it calls `registerForActivityResult`,
// which gives an `LifecycleOwners must call register before they are STARTED.` error when called outside the onCreate hook
Expand Down Expand Up @@ -336,6 +370,14 @@ impl InnerWebView {
URL_LOADING_OVERRIDE.get_or_init(move || UnsafeUrlLoadingOverride::new(i));
}

if let Some(h) = attributes.on_page_loading_handler {
ON_LOADING_HANDLER.get_or_init(move || UnsafeOnPageLoadingHandler::new(h));
}

if let Some(h) = attributes.on_page_loaded_handler {
ON_LOADED_HANDLER.get_or_init(move || UnsafeOnPageLoadedHandler::new(h));
}

Ok(Self { window })
}

Expand Down
24 changes: 24 additions & 0 deletions src/webview/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,12 @@ pub struct WebViewAttributes {

/// Whether all media can be played without user interaction.
pub autoplay: bool,

/// Set a handler closure to process to start of loading a new page.
pub on_page_loading_handler: Option<Box<dyn Fn(String)>>,

/// Set a handler closure to process when a new page has been loaded.
pub on_page_loaded_handler: Option<Box<dyn Fn(String)>>,
}

impl Default for WebViewAttributes {
Expand Down Expand Up @@ -263,6 +269,8 @@ impl Default for WebViewAttributes {
document_title_changed_handler: None,
incognito: false,
autoplay: true,
on_page_loading_handler: None,
on_page_loaded_handler: None,
}
}
}
Expand Down Expand Up @@ -629,6 +637,22 @@ impl<'a> WebViewBuilder<'a> {
self
}

/// Set a handler to process when a new page start loading.
///
/// The handler will be called when the webview begins loading the content for the new page.
pub fn with_on_page_loading_handler(mut self, handler: impl Fn(String) + 'static) -> Self {
self.webview.on_page_loading_handler = Some(Box::new(handler));
self
}

/// Set a handler to process when a new page has been loaded.
///
/// The handler will be called when the webview the content for the new page has been fully loaded.
pub fn with_on_page_loaded_handler(mut self, handler: impl Fn(String) + 'static) -> Self {
self.webview.on_page_loaded_handler = Some(Box::new(handler));
self
}

/// Consume the builder and create the [`WebView`].
///
/// Platform-specific behavior:
Expand Down
18 changes: 18 additions & 0 deletions src/webview/webkitgtk/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,24 @@ impl InnerWebView {
});
}

let on_page_loading_handler = attributes.on_page_loading_handler.take();
let on_page_loaded_handler = attributes.on_page_loaded_handler.take();
if on_page_loading_handler.is_some() || on_page_loaded_handler.is_some() {
webview.connect_load_changed(move |webview, load_event| match load_event {
LoadEvent::Committed => {
if let Some(ref f) = on_page_loading_handler {
f(webview.uri().unwrap().to_string());
}
}
LoadEvent::Finished => {
if let Some(ref f) = on_page_loaded_handler {
f(webview.uri().unwrap().to_string());
}
}
_ => (),
});
}

webview.add_events(
EventMask::POINTER_MOTION_MASK
| EventMask::BUTTON1_MOTION_MASK
Expand Down
46 changes: 39 additions & 7 deletions src/webview/webview2/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,38 @@ impl InnerWebView {
}
}

if let Some(on_page_loading_handler) = attributes.on_page_loading_handler {
unsafe {
webview
.add_ContentLoading(
jhutchins marked this conversation as resolved.
Show resolved Hide resolved
&ContentLoadingEventHandler::create(Box::new(move |webview, _| {
if let Some(webview) = webview {
on_page_loading_handler(url_from_webview(&webview))
}
Ok(())
})),
&mut token,
)
.map_err(webview2_com::Error::WindowsError)?;
}
}

if let Some(on_page_loaded_handler) = attributes.on_page_loaded_handler {
unsafe {
webview
.add_NavigationCompleted(
&NavigationCompletedEventHandler::create(Box::new(move |webview, _| {
if let Some(webview) = webview {
on_page_loaded_handler(url_from_webview(&webview))
}
Ok(())
})),
&mut token,
)
.map_err(webview2_com::Error::WindowsError)?;
}
}

// Initialize scripts
Self::add_script_to_execute_on_document_created(
&webview,
Expand Down Expand Up @@ -832,13 +864,7 @@ window.addEventListener('mousemove', (e) => window.chrome.webview.postMessage('_
}

pub fn url(&self) -> Url {
let mut pwstr = PWSTR::null();

unsafe { self.webview.Source(&mut pwstr).unwrap() };

let uri = take_pwstr(pwstr);

Url::parse(&uri).unwrap()
Url::parse(&url_from_webview(&self.webview)).unwrap()
}

pub fn eval(
Expand Down Expand Up @@ -1047,3 +1073,9 @@ fn get_windows_ver() -> Option<(u32, u32, u32)> {
None
}
}

fn url_from_webview(webview: &ICoreWebView2) -> String {
let mut pwstr = PWSTR::null();
unsafe { webview.Source(&mut pwstr).unwrap() };
take_pwstr(pwstr)
}
Loading