Struct tauri::plugin::Builder

source ·
pub struct Builder<R: Runtime, C: DeserializeOwned = ()> { /* private fields */ }
Expand description

Builds a TauriPlugin.

This Builder offers a more concise way to construct Tauri plugins than implementing the Plugin trait directly.

Conventions

When using the Builder Pattern it is encouraged to export a function called init that constructs and returns the plugin. While plugin authors can provide every possible way to construct a plugin, sticking to the init function convention helps users to quickly identify the correct function to call.

use tauri::{plugin::{Builder, TauriPlugin}, Runtime};

pub fn init<R: Runtime>() -> TauriPlugin<R> {
  Builder::new("example")
    .build()
}

When plugins expose more complex configuration options, it can be helpful to provide a Builder instead:

use tauri::{plugin::{Builder as PluginBuilder, TauriPlugin}, Runtime};

pub struct Builder {
  option_a: String,
  option_b: String,
  option_c: bool
}

impl Default for Builder {
  fn default() -> Self {
    Self {
      option_a: "foo".to_string(),
      option_b: "bar".to_string(),
      option_c: false
    }
  }
}

impl Builder {
  pub fn new() -> Self {
    Default::default()
  }

  pub fn option_a(mut self, option_a: String) -> Self {
    self.option_a = option_a;
    self
  }

  pub fn option_b(mut self, option_b: String) -> Self {
    self.option_b = option_b;
    self
  }

  pub fn option_c(mut self, option_c: bool) -> Self {
    self.option_c = option_c;
    self
  }

  pub fn build<R: Runtime>(self) -> TauriPlugin<R> {
    PluginBuilder::new("example")
      .setup(move |app_handle| {
        // use the options here to do stuff
        println!("a: {}, b: {}, c: {}", self.option_a, self.option_b, self.option_c);

        Ok(())
      })
      .build()
  }
}

Implementations§

Creates a new Plugin builder.

Defines the JS message handler callback. It is recommended you use the tauri::generate_handler to generate the input to this method, as the input type is not considered stable yet.

Examples
use tauri::{plugin::{Builder, TauriPlugin}, Runtime};

#[tauri::command]
async fn foobar<R: Runtime>(app: tauri::AppHandle<R>, window: tauri::Window<R>) -> Result<(), String> {
  println!("foobar");

  Ok(())
}

fn init<R: Runtime>() -> TauriPlugin<R> {
  Builder::new("example")
    .invoke_handler(tauri::generate_handler![foobar])
    .build()
}

Sets the provided JavaScript to 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.

The script is wrapped into its own context with (function () { /* your script here */ })();, so global variables must be assigned to window instead of implicity declared.

Note that calling this function multiple times overrides previous values.

Examples
use tauri::{plugin::{Builder, TauriPlugin}, 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 init<R: Runtime>() -> TauriPlugin<R> {
  Builder::new("example")
    .js_init_script(INIT_SCRIPT.to_string())
    .build()
}

Define a closure that runs when the plugin is registered.

This is a convenience function around setup_with_config, without the need to specify a configuration object.

The closure gets called before the setup_with_config closure.

Examples
use tauri::{plugin::{Builder, TauriPlugin}, Runtime, Manager};
use std::path::PathBuf;

#[derive(Debug, Default)]
struct PluginState {
   dir: Option<PathBuf>
}

fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("example")
  .setup(|app_handle| {
    app_handle.manage(PluginState::default());

    Ok(())
  })
  .build()
}

Define a closure that runs when the plugin is registered, accepting a configuration object set on tauri.conf.json > plugins > yourPluginName.

If your plugin is not pulling a configuration object from tauri.conf.json, use setup.

The closure gets called after the setup closure.

Examples
#[derive(serde::Deserialize)]
struct Config {
  api_url: String,
}

fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R, Config> {
  tauri::plugin::Builder::<R, Config>::new("api")
    .setup_with_config(|_app_handle, config| {
      println!("config: {:?}", config.api_url);
      Ok(())
    })
    .build()
}

tauri::Builder::default().plugin(init());

Callback invoked when the webview performs a navigation to a page.

Examples
use tauri::{plugin::{Builder, TauriPlugin}, Runtime};

fn init<R: Runtime>() -> TauriPlugin<R> {
  Builder::new("example")
    .on_page_load(|window, payload| {
      println!("Loaded URL {} in window {}", payload.url(), window.label());
    })
    .build()
}

Callback invoked when the webview is created.

Examples
use tauri::{plugin::{Builder, TauriPlugin}, Runtime};

fn init<R: Runtime>() -> TauriPlugin<R> {
  Builder::new("example")
    .on_webview_ready(|window| {
      println!("created window {}", window.label());
    })
    .build()
}

Callback invoked when the event loop receives a new event.

Examples
use tauri::{plugin::{Builder, TauriPlugin}, RunEvent, Runtime};

fn init<R: Runtime>() -> TauriPlugin<R> {
  Builder::new("example")
    .on_event(|app_handle, event| {
      match event {
        RunEvent::ExitRequested { api, .. } => {
          // Prevents the app from exiting.
          // This will cause the core thread to continue running in the background even without any open windows.
          api.prevent_exit();
        }
        // Ignore all other cases.
        _ => {}
      }
    })
    .build()
}

Callback invoked when the plugin is dropped.

Examples
use tauri::{plugin::{Builder, TauriPlugin}, Runtime};

fn init<R: Runtime>() -> TauriPlugin<R> {
  Builder::new("example")
    .on_drop(|app| {
      println!("plugin has been dropped and is no longer running");
      // you can run cleanup logic here
    })
    .build()
}

Builds the TauriPlugin.

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