Struct tauri::window::WindowBuilder

source ·
pub struct WindowBuilder<'a, R: Runtime = Wry> { /* private fields */ }
Expand description

A builder for a webview window managed by Tauri.

Implementations§

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

Examples
  • Create a window in the setup hook:
tauri::Builder::default()
  .setup(|app| {
    let window = tauri::WindowBuilder::new(app, "label", tauri::WindowUrl::App("index.html".into()))
      .build()?;
    Ok(())
  });
  • Create a window in a separate thread:
tauri::Builder::default()
  .setup(|app| {
    let handle = app.handle();
    std::thread::spawn(move || {
      let window = tauri::WindowBuilder::new(&handle, "label", tauri::WindowUrl::App("index.html".into()))
        .build()
        .unwrap();
    });
    Ok(())
  });
  • Create a window in a command:
#[tauri::command]
async fn create_window(app: tauri::AppHandle) {
  let window = tauri::WindowBuilder::new(&app, "label", tauri::WindowUrl::External("https://tauri.app/".parse().unwrap()))
    .build()
    .unwrap();
}
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 found in repository?
src/window.rs (line 738)
733
734
735
736
737
738
739
  pub fn builder<'a, M: Manager<R>, L: Into<String>>(
    manager: &'a M,
    label: L,
    url: WindowUrl,
  ) -> WindowBuilder<'a, R> {
    WindowBuilder::<'a, R>::new(manager, label.into(), url)
  }

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, WindowUrl},
  http::header::HeaderValue,
  window::WindowBuilder,
};
use std::collections::HashMap;
tauri::Builder::default()
  .setup(|app| {
    WindowBuilder::new(app, "core", WindowUrl::App("index.html".into()))
      .on_web_resource_request(|request, response| {
        if request.uri().starts_with("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(())
  });

Creates a new webview window.

Examples found in repository?
src/endpoints/window.rs (line 216)
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
  async fn create_webview<R: Runtime>(
    context: InvokeContext<R>,
    options: Box<WindowConfig>,
  ) -> super::Result<()> {
    let label = options.label.clone();
    let url = options.url.clone();
    let file_drop_enabled = options.file_drop_enabled;

    let mut builder = crate::window::Window::builder(&context.window, label, url);
    if !file_drop_enabled {
      builder = builder.disable_file_drop_handler();
    }

    builder.window_builder =
      <<R::Dispatcher as Dispatch<crate::EventLoopMessage>>::WindowBuilder>::with_config(*options);
    builder.build().map_err(crate::error::into_anyhow)?;

    Ok(())
  }

Sets the menu for the window.

Show window in the center of the screen.

The initial position of the window’s.

Window size.

Window min inner size.

Window max inner size.

Whether the window is resizable or not.

The title of the window in the title bar.

Whether to start the window in fullscreen or not.

Whether the window will be initially hidden or focused.

Whether the window should be maximized upon creation.

Whether the window should be immediately visible upon creation.

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

Platform-specific
  • macOS: Only supported on macOS 10.14+.
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.

Whether the window should have borders and bars.

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

Sets the window icon.

Sets whether or not the window icon should be added to the taskbar.

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::WindowBuilder::new(app, "label", tauri::WindowUrl::App("index.html".into()))
        .initialization_script(INIT_SCRIPT)
        .build()?;
      Ok(())
    });
}

Data directory for the webview.

Disables the file drop handler. This is required to use drag and drop APIs on the front end on Windows.

Examples found in repository?
src/endpoints/window.rs (line 211)
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
  async fn create_webview<R: Runtime>(
    context: InvokeContext<R>,
    options: Box<WindowConfig>,
  ) -> super::Result<()> {
    let label = options.label.clone();
    let url = options.url.clone();
    let file_drop_enabled = options.file_drop_enabled;

    let mut builder = crate::window::Window::builder(&context.window, label, url);
    if !file_drop_enabled {
      builder = builder.disable_file_drop_handler();
    }

    builder.window_builder =
      <<R::Dispatcher as Dispatch<crate::EventLoopMessage>>::WindowBuilder>::with_config(*options);
    builder.build().map_err(crate::error::into_anyhow)?;

    Ok(())
  }

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.

Trait Implementations§

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

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

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more