tauri::webview

Struct WebviewWindowBuilder

Source
pub struct WebviewWindowBuilder<'a, R: Runtime, M: Manager<R>> { /* private fields */ }
Expand description

A builder for WebviewWindow, a window that hosts a single webview.

Implementations§

Source§

impl<'a, R: Runtime, M: Manager<R>> WebviewWindowBuilder<'a, R, M>

Source

pub fn new<L: Into<String>>(manager: &'a M, label: L, url: WebviewUrl) -> Self

Initializes a webview window builder with the given window label.

§Known issues

On Windows, this function deadlocks when used in a synchronous command, see the Webview2 issue. You should use async commands when creating windows.

§Examples
  • Create a window in the setup hook:
tauri::Builder::default()
  .setup(|app| {
    let webview_window = tauri::WebviewWindowBuilder::new(app, "label", tauri::WebviewUrl::App("index.html".into()))
      .build()?;
    Ok(())
  });
  • Create a window in a separate thread:
tauri::Builder::default()
  .setup(|app| {
    let handle = app.handle().clone();
    std::thread::spawn(move || {
      let webview_window = tauri::WebviewWindowBuilder::new(&handle, "label", tauri::WebviewUrl::App("index.html".into()))
        .build()
        .unwrap();
    });
    Ok(())
  });
  • Create a window in a command:
#[tauri::command]
async fn create_window(app: tauri::AppHandle) {
  let webview_window = tauri::WebviewWindowBuilder::new(&app, "label", tauri::WebviewUrl::App("index.html".into()))
    .build()
    .unwrap();
}
Source

pub fn from_config(manager: &'a M, config: &WindowConfig) -> Result<Self>

Initializes a webview window builder from a WindowConfig from tauri.conf.json. Keep in mind that you can’t create 2 windows with the same label so make sure that the initial window was closed or change the label of the new WebviewWindowBuilder.

§Known issues

On Windows, this function deadlocks when used in a synchronous command, see the Webview2 issue. You should use async commands when creating windows.

§Examples
  • Create a window in a command:
#[tauri::command]
async fn reopen_window(app: tauri::AppHandle) {
  let webview_window = tauri::WebviewWindowBuilder::from_config(&app, &app.config().app.windows.get(0).unwrap().clone())
    .unwrap()
    .build()
    .unwrap();
}
Source

pub fn on_menu_event<F: Fn(&Window<R>, MenuEvent) + Send + Sync + 'static>( self, f: F, ) -> Self

Registers a global menu event listener.

Note that this handler is called for any menu event, whether it is coming from this window, another window or from the tray icon menu.

Also note that this handler will not be called if the window used to register it was closed.

§Examples
use tauri::menu::{Menu, Submenu, MenuItem};
tauri::Builder::default()
  .setup(|app| {
    let handle = app.handle();
    let save_menu_item = MenuItem::new(handle, "Save", true, None::<&str>)?;
    let menu = Menu::with_items(handle, &[
      &Submenu::with_items(handle, "File", true, &[
        &save_menu_item,
      ])?,
    ])?;
    let webview_window = tauri::WebviewWindowBuilder::new(app, "editor", tauri::WebviewUrl::App("index.html".into()))
      .menu(menu)
      .on_menu_event(move |window, event| {
        if event.id == save_menu_item.id() {
          // save menu item
        }
      })
      .build()
      .unwrap();

    Ok(())
  });
Source

pub fn on_web_resource_request<F: Fn(Request<Vec<u8>>, &mut Response<Cow<'static, [u8]>>) + Send + Sync + 'static>( self, f: F, ) -> Self

Defines a closure to be executed when the webview makes an HTTP request for a web resource, allowing you to modify the response.

Currently only implemented for the tauri URI protocol.

NOTE: Currently this is not executed when using external URLs such as a development server, but it might be implemented in the future. Always check the request URL.

§Examples
use tauri::{
  utils::config::{Csp, CspDirectiveSources, WebviewUrl},
  webview::WebviewWindowBuilder,
};
use http::header::HeaderValue;
use std::collections::HashMap;
tauri::Builder::default()
  .setup(|app| {
    let webview_window = WebviewWindowBuilder::new(app, "core", WebviewUrl::App("index.html".into()))
      .on_web_resource_request(|request, response| {
        if request.uri().scheme_str() == Some("tauri") {
          // if we have a CSP header, Tauri is loading an HTML file
          //  for this example, let's dynamically change the CSP
          if let Some(csp) = response.headers_mut().get_mut("Content-Security-Policy") {
            // use the tauri helper to parse the CSP policy to a map
            let mut csp_map: HashMap<String, CspDirectiveSources> = Csp::Policy(csp.to_str().unwrap().to_string()).into();
            csp_map.entry("script-src".to_string()).or_insert_with(Default::default).push("'unsafe-inline'");
            // use the tauri helper to get a CSP string from the map
            let csp_string = Csp::from(csp_map).to_string();
            *csp = HeaderValue::from_str(&csp_string).unwrap();
          }
        }
      })
      .build()?;
    Ok(())
  });
Source

pub fn on_navigation<F: Fn(&Url) -> bool + Send + 'static>(self, f: F) -> Self

Defines a closure to be executed when the webview navigates to a URL. Returning false cancels the navigation.

§Examples
use tauri::{
  utils::config::{Csp, CspDirectiveSources, WebviewUrl},
  webview::WebviewWindowBuilder,
};
use http::header::HeaderValue;
use std::collections::HashMap;
tauri::Builder::default()
  .setup(|app| {
    let webview_window = WebviewWindowBuilder::new(app, "core", WebviewUrl::App("index.html".into()))
      .on_navigation(|url| {
        // allow the production URL or localhost on dev
        url.scheme() == "tauri" || (cfg!(dev) && url.host_str() == Some("localhost"))
      })
      .build()?;
    Ok(())
  });
Source

pub fn on_download<F: Fn(Webview<R>, DownloadEvent<'_>) -> bool + Send + Sync + 'static>( self, f: F, ) -> Self

Set a download event handler to be notified when a download is requested or finished.

Returning false prevents the download from happening on a DownloadEvent::Requested event.

§Examples
use tauri::{
  utils::config::{Csp, CspDirectiveSources, WebviewUrl},
  webview::{DownloadEvent, WebviewWindowBuilder},
};

tauri::Builder::default()
  .setup(|app| {
    let handle = app.handle();
    let webview_window = WebviewWindowBuilder::new(handle, "core", WebviewUrl::App("index.html".into()))
      .on_download(|webview, event| {
        match event {
          DownloadEvent::Requested { url, destination } => {
            println!("downloading {}", url);
            *destination = "/home/tauri/target/path".into();
          }
          DownloadEvent::Finished { url, path, success } => {
            println!("downloaded {} to {:?}, success: {}", url, path, success);
          }
          _ => (),
        }
        // let the download start
        true
      })
      .build()?;

    Ok(())
  });
Source

pub fn on_page_load<F: Fn(WebviewWindow<R>, PageLoadPayload<'_>) + Send + Sync + 'static>( self, f: F, ) -> Self

Defines a closure to be executed when a page load event is triggered. The event can be either tauri_runtime::webview::PageLoadEvent::Started if the page has started loading or tauri_runtime::webview::PageLoadEvent::Finished when the page finishes loading.

§Examples
use tauri::{
  utils::config::{Csp, CspDirectiveSources, WebviewUrl},
  webview::{PageLoadEvent, WebviewWindowBuilder},
};
use http::header::HeaderValue;
use std::collections::HashMap;
tauri::Builder::default()
  .setup(|app| {
    let webview_window = WebviewWindowBuilder::new(app, "core", WebviewUrl::App("index.html".into()))
      .on_page_load(|window, payload| {
        match payload.event() {
          PageLoadEvent::Started => {
            println!("{} finished loading", payload.url());
          }
          PageLoadEvent::Finished => {
            println!("{} finished loading", payload.url());
          }
        }
      })
      .build()?;
    Ok(())
  });
Source

pub fn build(self) -> Result<WebviewWindow<R>>

Creates a new window.

Source§

impl<'a, R: Runtime, M: Manager<R>> WebviewWindowBuilder<'a, R, M>

Desktop APIs.

Source

pub fn menu(self, menu: Menu<R>) -> Self

Sets the menu for the window.

Source

pub fn center(self) -> Self

Show window in the center of the screen.

Source

pub fn position(self, x: f64, y: f64) -> Self

The initial position of the window’s.

Source

pub fn inner_size(self, width: f64, height: f64) -> Self

Window size.

Source

pub fn min_inner_size(self, min_width: f64, min_height: f64) -> Self

Window min inner size.

Source

pub fn max_inner_size(self, max_width: f64, max_height: f64) -> Self

Window max inner size.

Source

pub fn inner_size_constraints(self, constraints: WindowSizeConstraints) -> Self

Window inner size constraints.

Source

pub fn resizable(self, resizable: bool) -> Self

Whether the window is resizable or not. When resizable is set to false, native window’s maximize button is automatically disabled.

Source

pub fn maximizable(self, maximizable: bool) -> Self

Whether the window’s native maximize button is enabled or not. If resizable is set to false, this setting is ignored.

§Platform-specific
  • macOS: Disables the “zoom” button in the window titlebar, which is also used to enter fullscreen mode.
  • Linux / iOS / Android: Unsupported.
Source

pub fn minimizable(self, minimizable: bool) -> Self

Whether the window’s native minimize button is enabled or not.

§Platform-specific
  • Linux / iOS / Android: Unsupported.
Source

pub fn closable(self, closable: bool) -> Self

Whether the window’s native close button is enabled or not.

§Platform-specific
  • Linux: “GTK+ will do its best to convince the window manager not to show a close button. Depending on the system, this function may not have any effect when called on a window that is already visible”
  • iOS / Android: Unsupported.
Source

pub fn title<S: Into<String>>(self, title: S) -> Self

The title of the window in the title bar.

Source

pub fn fullscreen(self, fullscreen: bool) -> Self

Whether to start the window in fullscreen or not.

Source

pub fn focus(self) -> Self

👎Deprecated since 1.2.0: The window is automatically focused by default. This function Will be removed in 3.0.0. Use focused instead.

Sets the window to be initially focused.

Source

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

Whether the window will be initially focused or not.

Source

pub fn maximized(self, maximized: bool) -> Self

Whether the window should be maximized upon creation.

Source

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

Whether the window should be immediately visible upon creation.

Source

pub fn theme(self, theme: Option<Theme>) -> Self

Forces a theme or uses the system settings if None was provided.

§Platform-specific
  • macOS: Only supported on macOS 10.14+.
Source

pub fn decorations(self, decorations: bool) -> Self

Whether the window should have borders and bars.

Source

pub fn always_on_bottom(self, always_on_bottom: bool) -> Self

Whether the window should always be below other windows.

Source

pub fn always_on_top(self, always_on_top: bool) -> Self

Whether the window should always be on top of other windows.

Source

pub fn visible_on_all_workspaces(self, visible_on_all_workspaces: bool) -> Self

Whether the window will be visible on all workspaces or virtual desktops.

Source

pub fn content_protected(self, protected: bool) -> Self

Prevents the window contents from being captured by other apps.

Source

pub fn icon(self, icon: Image<'a>) -> Result<Self>

Sets the window icon.

Source

pub fn skip_taskbar(self, skip: bool) -> Self

Sets whether or not the window icon should be hidden from the taskbar.

§Platform-specific
  • macOS: Unsupported.
Source

pub fn window_classname<S: Into<String>>(self, classname: S) -> Self

Sets custom name for Windows’ window class. Windows only.

Source

pub fn shadow(self, enable: bool) -> Self

Sets whether or not the window has shadow.

§Platform-specific
  • Windows:
    • false has no effect on decorated window, shadows are always ON.
    • true will make undecorated window have a 1px white border, and on Windows 11, it will have a rounded corners.
  • Linux: Unsupported.
Source

pub fn parent(self, parent: &WebviewWindow<R>) -> Result<Self>

Sets a parent to the window to be created.

§Platform-specific
Source

pub fn transient_for(self, parent: &WebviewWindow<R>) -> Result<Self>

Sets the window to be created transient for parent.

See https://docs.gtk.org/gtk3/method.Window.set_transient_for.html

Source

pub fn transient_for_raw(self, parent: &impl IsA<Window>) -> Self

Sets the window to be created transient for parent.

See https://docs.gtk.org/gtk3/method.Window.set_transient_for.html

Source

pub fn effects(self, effects: WindowEffectsConfig) -> Self

Sets window effects.

Requires the window to be transparent.

§Platform-specific:
Source§

impl<'a, R: Runtime, M: Manager<R>> WebviewWindowBuilder<'a, R, M>

Webview attributes.

Source

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

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

Source

pub fn initialization_script(self, script: &str) -> Self

Adds the provided JavaScript to a list of scripts that should be run after the global object has been created, but before the HTML document has been parsed and before any other script included by the HTML document is run.

Since it runs on all top-level document and child frame page navigations, it’s recommended to check the window.location to guard your script from running on unexpected origins.

§Examples
use tauri::{WebviewWindowBuilder, Runtime};

const INIT_SCRIPT: &str = r#"
  if (window.location.origin === 'https://tauri.app') {
    console.log("hello world from js init script");

    window.__MY_CUSTOM_PROPERTY__ = { foo: 'bar' };
  }
"#;

fn main() {
  tauri::Builder::default()
    .setup(|app| {
      let webview = tauri::WebviewWindowBuilder::new(app, "label", tauri::WebviewUrl::App("index.html".into()))
        .initialization_script(INIT_SCRIPT)
        .build()?;
      Ok(())
    });
}
Source

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

Set the user agent for the webview

Source

pub fn additional_browser_args(self, additional_args: &str) -> Self

Set additional arguments for the webview.

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

By default wry passes --disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection so if you use this method, you also need to disable these components by yourself if you want.

Source

pub fn data_directory(self, data_directory: PathBuf) -> Self

Data directory for the webview.

Source

pub fn disable_drag_drop_handler(self) -> Self

Disables the drag and drop handler. This is required to use HTML5 drag and drop APIs on the frontend on Windows.

Source

pub fn enable_clipboard_access(self) -> 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 you still need to add menu item accelerators to use shortcuts.

Source

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

Enable or disable incognito mode for the WebView..

§Platform-specific:

Android: Unsupported.

Source

pub fn auto_resize(self) -> Self

Sets the webview to automatically grow and shrink its size and position when the parent window resizes.

Source

pub fn proxy_url(self, url: Url) -> Self

Set a proxy URL for the WebView for all network requests.

Must be either a http:// or a socks5:// URL.

Source

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

Available on non-macOS or crate feature macos-private-api only.

Whether the window should be transparent. If this is true, writing colors with alpha values different than 1.0 will produce a transparent window.

Source

pub fn zoom_hotkeys_enabled(self, enabled: bool) -> Self

Whether page zooming by hotkeys is enabled

§Platform-specific:
  • Windows: Controls WebView2’s IsZoomControlEnabled setting.

  • MacOS / Linux: Injects a polyfill that zooms in and out with ctrl/command + -/=, 20% in each step, ranging from 20% to 1000%. Requires webview:allow-set-webview-zoom permission

  • Android / iOS: Unsupported.

Source

pub fn browser_extensions_enabled(self, enabled: bool) -> Self

Whether browser extensions can be installed for the webview process

§Platform-specific:
Source

pub fn use_https_scheme(self, enabled: bool) -> Self

Sets whether the custom protocols should use https://<scheme>.localhost instead of the default http://<scheme>.localhost on Windows and Android. Defaults to false.

§Note

Using a https scheme will NOT allow mixed content when trying to fetch http endpoints and therefore will not match the behavior of the <scheme>://localhost protocols used on macOS and Linux.

§Warning

Changing this value between releases will change the IndexedDB, cookies and localstorage location and your app will not be able to access the old data.

Source

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

Whether web inspector, which is usually called browser devtools, is enabled or not. Enabled by default.

This API works in debug builds, but requires devtools feature flag to enable it in release builds.

§Platform-specific
  • macOS: This will call private functions on macOS.
  • 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 background_color(self, color: Color) -> Self

Set the window and webview background color.

§Platform-specific:
  • Android / iOS: Unsupported for the window layer.
  • macOS / iOS: Not implemented for the webview layer.
  • Windows:
    • alpha channel is ignored for the window layer.
    • On Windows 7, alpha channel is ignored for the webview layer.
    • On Windows 8 and newer, if alpha channel is not 0, it will be ignored.

Auto Trait Implementations§

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>,

Source§

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>,

Source§

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.
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T