diff --git a/.changes/with_focused.md b/.changes/with_focused.md new file mode 100644 index 000000000..4037487e6 --- /dev/null +++ b/.changes/with_focused.md @@ -0,0 +1,5 @@ +--- +"wry": "patch" +--- + +Add `WebViewAtrributes.focused` and `WebViewBuilder::with_focused` to control whether to focus the webview upon creation or not. Supported on Windows and Linux only. diff --git a/src/webview/mod.rs b/src/webview/mod.rs index a8ba6faea..313623033 100644 --- a/src/webview/mod.rs +++ b/src/webview/mod.rs @@ -243,6 +243,13 @@ pub struct WebViewAttributes { /// - **macOS**: Requires macOS 14.0+ and the `mac-proxy` feature flag to be enabled. /// - **Android / iOS:** Not supported. pub proxy_config: Option, + + /// Whether the webview should be focused when created. + /// + /// ## Platform-specific: + /// + /// - **macOS / Android / iOS:** Unsupported. + pub focused: bool, } impl Default for WebViewAttributes { @@ -276,6 +283,7 @@ impl Default for WebViewAttributes { autoplay: true, on_page_load_handler: None, proxy_config: None, + focused: true, } } } @@ -674,6 +682,16 @@ impl<'a> WebViewBuilder<'a> { self } + /// Set whether the webview should be focused when created. + /// + /// ## Platform-specific: + /// + /// - **macOS / Android / iOS:** Unsupported. + pub fn with_focused(mut self, focused: bool) -> Self { + self.webview.focused = focused; + self + } + /// Consume the builder and create the [`WebView`]. /// /// Platform-specific behavior: diff --git a/src/webview/webkitgtk/mod.rs b/src/webview/webkitgtk/mod.rs index 85ed28117..dc8d85bbd 100644 --- a/src/webview/webkitgtk/mod.rs +++ b/src/webview/webkitgtk/mod.rs @@ -222,7 +222,10 @@ impl InnerWebView { } else { window.add(&*webview); } - webview.grab_focus(); + + if attributes.focused { + webview.grab_focus(); + } if let Some(context) = WebViewExt::context(&*webview) { use webkit2gtk::WebContextExt; diff --git a/src/webview/webview2/mod.rs b/src/webview/webview2/mod.rs index 439008061..a47ccf83a 100644 --- a/src/webview/webview2/mod.rs +++ b/src/webview/webview2/mod.rs @@ -846,9 +846,11 @@ window.addEventListener('mousemove', (e) => window.chrome.webview.postMessage('_ controller .SetIsVisible(true) .map_err(webview2_com::Error::WindowsError)?; - controller - .MoveFocus(COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC) - .map_err(webview2_com::Error::WindowsError)?; + if attributes.focused { + controller + .MoveFocus(COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC) + .map_err(webview2_com::Error::WindowsError)?; + } } Ok(webview)