Struct wry::WebViewBuilder

source ·
pub struct WebViewBuilder<'a> {
    pub attrs: WebViewAttributes,
    /* private fields */
}
Expand description

Builder type of WebView.

WebViewBuilder / WebView are the basic building blocks to construct WebView contents and scripts for those who prefer to control fine grained window creation and event handling. WebViewBuilder provides ability to setup initialization before web engine starts.

Fields§

§attrs: WebViewAttributes

Implementations§

source§

impl<'a> WebViewBuilder<'a>

source

pub fn new(window: &'a impl HasWindowHandle) -> Self

Create a WebViewBuilder from a type that implements HasWindowHandle.

§Platform-specific:
  • Linux: Only X11 is supported, if you want to support Wayland too, use [WebViewBuilderExtUnix::new_gtk].

    Although this methods only needs an X11 window handle, we use webkit2gtk, so you still need to initialize gtk by callling [gtk::init] and advance its loop alongside your event loop using [gtk::main_iteration_do]. Checkout the Platform Considerations section in the crate root documentation.

  • Windows: The webview will auto-resize when the passed handle is resized.

  • Linux (X11): Unlike macOS and Windows, the webview will not auto-resize and you’ll need to call WebView::set_bounds manually.

§Panics:
  • Panics if the provided handle was not supported or invalid.
  • Panics on Linux, if [gtk::init] was not called in this thread.
source

pub fn new_as_child(parent: &'a impl HasWindowHandle) -> Self

Create WebViewBuilder as a child window inside the provided HasWindowHandle.

§Platform-specific
  • Windows: This will create the webview as a child window of the parent window.

  • macOS: This will create the webview as a NSView subview of the parent window’s content view.

  • Linux: This will create the webview as a child window of the parent window. Only X11 is supported. This method won’t work on Wayland.

    Although this methods only needs an X11 window handle, you use webkit2gtk, so you still need to initialize gtk by callling [gtk::init] and advance its loop alongside your event loop using [gtk::main_iteration_do]. Checkout the Platform Considerations section in the crate root documentation.

    If you want to support child webviews on X11 and Wayland at the same time, we recommend using [WebViewBuilderExtUnix::new_gtk] with [gtk::Fixed].

  • Android/iOS: Unsupported.

§Panics:
  • Panics if the provided handle was not support or invalid.
  • Panics on Linux, if [gtk::init] was not called in this thread.
source

pub fn with_back_forward_navigation_gestures(self, gesture: bool) -> Self

Indicates whether horizontal swipe gestures trigger backward and forward page navigation.

§Platform-specific:
  • Android / iOS: Unsupported.
source

pub fn with_transparent(self, transparent: bool) -> Self

Sets whether the WebView should be transparent.

§Platform-specific:

Windows 7: Not supported.

source

pub fn with_background_color(self, background_color: RGBA) -> Self

Specify the webview background color. This will be ignored if transparent is set to true.

The color uses the RGBA format.

§Platfrom-specific:
  • macOS / iOS: Not implemented.
  • Windows:
    • on Windows 7, transparency is not supported and the alpha value will be ignored.
    • on Windows higher than 7: translucent colors are not supported so any alpha value other than 0 will be replaced by 255
source

pub fn with_visible(self, visible: bool) -> Self

Sets whether the WebView should be visible or not.

source

pub fn with_autoplay(self, autoplay: bool) -> Self

Sets whether all media can be played without user interaction.

source

pub fn with_initialization_script(self, js: &str) -> Self

Initialize javascript code when loading new pages. When webview load a new page, this initialization code will be executed. It is guaranteed that code is executed before window.onload.

§Platform-specific
  • Android: When addDocumentStartJavaScript is not supported, we prepend them to each HTML head (implementation only supported on custom protocol URLs). For remote URLs, we use onPageStarted which is not guaranteed to run before other scripts.
source

pub fn with_custom_protocol<F>(self, name: String, handler: F) -> Self
where F: Fn(Request<Vec<u8>>) -> Response<Cow<'static, [u8]>> + 'static,

Register custom loading protocols with pairs of scheme uri string and a handling closure.

The closure takes a Request and returns a Response

§Warning

Pages loaded from custom protocol will have different Origin on different platforms. And servers which enforce CORS will need to add exact same Origin header in Access-Control-Allow-Origin if you wish to send requests with native fetch and XmlHttpRequest APIs. Here are the different Origin headers across platforms:

  • macOS, iOS and Linux: <scheme_name>://<path> (so it will be `wry://path/to/page).
  • Windows and Android: http://<scheme_name>.<path> by default (so it will be http://wry.path/to/page). To use https instead of http, use WebViewBuilderExtWindows::with_https_scheme and [WebViewBuilderExtAndroid::with_https_scheme].
§Reading assets on mobile
  • Android: For loading content from the assets folder (which is copied to the Andorid apk) please use the function [with_asset_loader] from [WebViewBuilderExtAndroid] instead. This function on Android can only be used to serve assets you can embed in the binary or are elsewhere in Android (provided the app has appropriate access), but not from the assets folder which lives within the apk. For the cases where this can be used, it works the same as in macOS and Linux.
  • iOS: To get the path of your assets, you can call CFBundle::resources_path. So url like wry://assets/index.html could get the html file in assets directory.
source

pub fn with_asynchronous_custom_protocol<F>( self, name: String, handler: F ) -> Self
where F: Fn(Request<Vec<u8>>, RequestAsyncResponder) + 'static,

Same as Self::with_custom_protocol but with an asynchronous responder.

§Examples
use wry::{WebViewBuilder, raw_window_handle};

WebViewBuilder::new(&window)
  .with_asynchronous_custom_protocol("wry".into(), |request, responder| {
    // here you can use a tokio task, thread pool or anything
    // to do heavy computation to resolve your request
    // e.g. downloading files, opening the camera...
    std::thread::spawn(move || {
      std::thread::sleep(std::time::Duration::from_secs(2));
      responder.respond(http::Response::builder().body(Vec::new()).unwrap());
    });
  });
source

pub fn with_ipc_handler<F>(self, handler: F) -> Self
where F: Fn(Request<String>) + 'static,

Set the IPC handler to receive the message from Javascript on webview using window.ipc.postMessage("insert_message_here") to host Rust code.

§Platform-specific
  • Linux / Android: The request URL is not supported on iframes and the main frame URL is used instead.
source

pub fn with_drag_drop_handler<F>(self, handler: F) -> Self
where F: Fn(DragDropEvent) -> bool + 'static,

Available on crate feature drag-drop only.

Set a handler closure to process incoming DragDropEvent of the webview.

§Blocking OS Default Behavior

Return true in the callback to block the OS’ default behavior.

Note, that if you do block this behavior, it won’t be possible to drop files on <input type="file"> forms. Also note, that it’s not possible to manually set the value of a <input type="file"> via JavaScript for security reasons.

source

pub fn with_url_and_headers( self, url: impl Into<String>, headers: HeaderMap ) -> Self

Load the provided URL with given headers when the builder calling WebViewBuilder::build to create the WebView. The provided URL must be valid.

§Note

Data URLs are not supported, use html option instead.

source

pub fn with_url(self, url: impl Into<String>) -> Self

Load the provided URL when the builder calling WebViewBuilder::build to create the WebView. The provided URL must be valid.

§Note

Data URLs are not supported, use html option instead.

source

pub fn with_headers(self, headers: HeaderMap) -> Self

Set headers used when loading the requested url.

source

pub fn with_html(self, html: impl Into<String>) -> Self

Load the provided HTML string when the builder calling WebViewBuilder::build to create the WebView. This will be ignored if url is provided.

§Warning

The Page loaded from html string will have null origin.

§PLatform-specific:
  • Windows: the string can not be larger than 2 MB (2 * 1024 * 1024 bytes) in total size
source

pub fn with_web_context(self, web_context: &'a mut WebContext) -> Self

Set the web context that can be shared with multiple WebViews.

source

pub fn with_user_agent(self, user_agent: &str) -> Self

Set a custom user-agent for the WebView.

source

pub fn with_devtools(self, devtools: bool) -> Self

Enable or disable web inspector which is usually called devtools.

Note this only enables devtools to the webview. To open it, you can call WebView::open_devtools, or right click the page and open it from the context menu.

§Platform-specific
  • macOS: This will call private functions on macOS. It is enabled in debug builds, but requires devtools feature flag to actually enable it in release builds.
  • Android: Open chrome://inspect/#devices in Chrome to get the devtools window. Wry’s WebView devtools API isn’t supported on Android.
  • iOS: Open Safari > Develop > [Your Device Name] > [Your WebView] to get the devtools window.
source

pub fn with_hotkeys_zoom(self, zoom: bool) -> Self

Whether page zooming by hotkeys or gestures is enabled

§Platform-specific

macOS / Linux / Android / iOS: Unsupported

source

pub fn with_navigation_handler( self, callback: impl Fn(String) -> bool + 'static ) -> Self

Set a navigation handler to decide if incoming url is allowed to navigate.

The closure take a String parameter as url and returns a bool to determine whether the navigation should happen. true allows to navigate and false does not.

source

pub fn with_download_started_handler( self, started_handler: impl FnMut(String, &mut PathBuf) -> bool + 'static ) -> Self

Set a download started handler to manage incoming downloads.

second is a mutable PathBuf reference that (possibly) represents where the file will be downloaded to. The latter parameter can be used to set the download location by assigning a new path to it, the assigned path must be absolute. The closure returns a bool to allow or deny the download.

source

pub fn with_download_completed_handler( self, download_completed_handler: impl Fn(String, Option<PathBuf>, bool) + 'static ) -> Self

Sets a download completion handler to manage downloads that have finished.

The closure is fired when the download completes, whether it was successful or not. The closure takes a String representing the URL of the original download request, an Option<PathBuf> potentially representing the filesystem path the file was downloaded to, and a bool indicating if the download succeeded. A value of None being passed instead of a PathBuf does not necessarily indicate that the download did not succeed, and may instead indicate some other failure, always check the third parameter if you need to know if the download succeeded.

§Platform-specific:
  • macOS: The second parameter indicating the path the file was saved to, is always empty, due to API limitations.
source

pub fn with_clipboard(self, clipboard: bool) -> Self

Enables clipboard access for the page rendered on Linux and Windows.

macOS doesn’t provide such method and is always enabled by default. But your app will still need to add menu item accelerators to use the clipboard shortcuts.

source

pub fn with_new_window_req_handler( self, callback: impl Fn(String) -> bool + 'static ) -> Self

Set a new window request handler to decide if incoming url is allowed to be opened.

The closure take a String parameter as url and return bool to determine whether the window should open. true allows to open and false does not.

source

pub fn with_accept_first_mouse(self, accept_first_mouse: bool) -> Self

Sets whether clicking an inactive window also clicks through to the webview. Default is false.

§Platform-specific

This configuration only impacts macOS.

source

pub fn with_document_title_changed_handler( self, callback: impl Fn(String) + 'static ) -> Self

Set a handler closure to process the change of the webview’s document title.

source

pub fn with_incognito(self, incognito: bool) -> Self

Run the WebView with incognito mode. Note that WebContext will be ingored if incognito is enabled.

§Platform-specific:
  • Android: Unsupported yet.
source

pub fn with_on_page_load_handler( self, handler: impl Fn(PageLoadEvent, String) + 'static ) -> Self

Set a handler to process page loading events.

source

pub fn with_proxy_config(self, configuration: ProxyConfig) -> Self

Set a proxy configuration for the webview.

  • macOS: Requires macOS 14.0+ and the mac-proxy feature flag to be enabled. Supports HTTP CONNECT and SOCKSv5 proxies.
  • Windows / Linux: Supports HTTP CONNECT and SOCKSv5 proxies.
  • Android / iOS: Not supported.
source

pub fn with_focused(self, focused: bool) -> Self

Set whether the webview should be focused when created.

§Platform-specific:
  • macOS / Android / iOS: Unsupported.
source

pub fn with_bounds(self, bounds: Rect) -> Self

Specify the webview position relative to its parent if it will be created as a child or if created using [WebViewBuilderExtUnix::new_gtk] with [gtk::Fixed].

Defaults to x: 0, y: 0, width: 200, height: 200.

source

pub fn build(self) -> Result<WebView>

Consume the builder and create the WebView.

§Panics:
  • Panics if the provided handle was not support or invalid.
  • Panics on Linux, if [gtk::init] was not called in this thread.

Trait Implementations§

source§

impl WebViewBuilderExtWindows for WebViewBuilder<'_>

source§

fn with_additional_browser_args<S: Into<String>>( self, additional_args: S ) -> Self

Pass additional args to WebView2 upon creating the webview. Read more
source§

fn with_browser_accelerator_keys(self, enabled: bool) -> Self

Determines whether browser-specific accelerator keys are enabled. When this setting is set to false, it disables all accelerator keys that access features specific to a web browser. The default value is true. See the following link to know more details. Read more
source§

fn with_theme(self, theme: Theme) -> Self

Specifies the theme of webview2. This affects things like prefers-color-scheme. Read more
source§

fn with_https_scheme(self, enabled: bool) -> Self

Determines whether the custom protocols should use https://<scheme>.path/to/page instead of the default http://<scheme>.path/to/page. Read more

Auto Trait Implementations§

§

impl<'a> Freeze for WebViewBuilder<'a>

§

impl<'a> !RefUnwindSafe for WebViewBuilder<'a>

§

impl<'a> !Send for WebViewBuilder<'a>

§

impl<'a> !Sync for WebViewBuilder<'a>

§

impl<'a> Unpin for WebViewBuilder<'a>

§

impl<'a> !UnwindSafe for WebViewBuilder<'a>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.