pub struct WebviewBuilder<R: Runtime> { /* private fields */ }
Available on crate feature unstable only.
Expand description

A builder for a webview.

Implementations§

source§

impl<R: Runtime> WebviewBuilder<R>

source

pub fn new<L: Into<String>>(label: L, url: WebviewUrl) -> Self

Initializes a webview builder with the given webview label and URL to load.

§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 webview in the setup hook:
tauri::Builder::default()
  .setup(|app| {
    let window = tauri::window::WindowBuilder::new(app, "label").build()?;
    let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::App("index.html".into()));
    let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap());
    Ok(())
  });
  • Create a webview in a separate thread:
tauri::Builder::default()
  .setup(|app| {
    let handle = app.handle().clone();
    std::thread::spawn(move || {
      let window = tauri::window::WindowBuilder::new(&handle, "label").build().unwrap();
      let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::App("index.html".into()));
      window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap());
    });
    Ok(())
  });
  • Create a webview in a command:
#[tauri::command]
async fn create_window(app: tauri::AppHandle) {
  let window = tauri::window::WindowBuilder::new(&app, "label").build().unwrap();
  let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::External("https://tauri.app/".parse().unwrap()));
  window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap());
}
source

pub fn from_config(config: &WindowConfig) -> Self

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

§Known issues

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

§Examples
  • Create a webview in a command:
#[tauri::command]
async fn reopen_window(app: tauri::AppHandle) {
  let window = tauri::window::WindowBuilder::from_config(&app, &app.config().app.windows.get(0).unwrap().clone())
    .unwrap()
    .build()
    .unwrap();
}
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},
  window::WindowBuilder,
  webview::WebviewBuilder,
};
use http::header::HeaderValue;
use std::collections::HashMap;
tauri::Builder::default()
  .setup(|app| {
    let window = tauri::window::WindowBuilder::new(app, "label").build()?;

    let webview_builder = WebviewBuilder::new("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();
          }
        }
      });

    let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;

    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},
  window::WindowBuilder,
  webview::WebviewBuilder,
};
use http::header::HeaderValue;
use std::collections::HashMap;
tauri::Builder::default()
  .setup(|app| {
    let window = tauri::window::WindowBuilder::new(app, "label").build()?;

    let webview_builder = WebviewBuilder::new("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"))
      });

    let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
    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},
  window::WindowBuilder,
  webview::{DownloadEvent, WebviewBuilder},
};

tauri::Builder::default()
  .setup(|app| {
    let window = WindowBuilder::new(app, "label").build()?;
    let webview_builder = WebviewBuilder::new("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
      });

    let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
    Ok(())
  });
source

pub fn on_page_load<F: Fn(Webview<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 PageLoadEvent::Started if the page has started loading or PageLoadEvent::Finished when the page finishes loading.

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

impl<R: Runtime> WebviewBuilder<R>

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::{WindowBuilder, 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 window = tauri::window::WindowBuilder::new(app, "label").build()?;
      let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::App("index.html".into()))
        .initialization_script(INIT_SCRIPT);
      let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
      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_file_drop_handler(self) -> Self

Disables the file drop handler. This is required to use drag and drop APIs on the front end 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 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.

§Platform-specific
  • macOS: Requires the macos-proxy feature flag and only compiles for macOS 14+.
source

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

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

Enable or disable transparency for the WebView.

source

pub fn auto_resize(self) -> Self

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

Auto Trait Implementations§

§

impl<R> !RefUnwindSafe for WebviewBuilder<R>

§

impl<R> Send for WebviewBuilder<R>

§

impl<R> !Sync for WebviewBuilder<R>

§

impl<R> Unpin for WebviewBuilder<R>

§

impl<R> !UnwindSafe for WebviewBuilder<R>

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.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more