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, api| {
// use the options here to do stuff
println!("a: {}, b: {}, c: {}", self.option_a, self.option_b, self.option_c);
Ok(())
})
.build()
}
}Implementations§
Source§impl<R: Runtime, C: DeserializeOwned> Builder<R, C>
impl<R: Runtime, C: DeserializeOwned> Builder<R, C>
Sourcepub fn invoke_handler<F>(self, invoke_handler: F) -> Self
pub fn invoke_handler<F>(self, invoke_handler: F) -> Self
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()
}
Sourcepub fn js_init_script(self, js_init_script: impl Into<String>) -> Self
pub fn js_init_script(self, js_init_script: impl Into<String>) -> Self
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.
The script is wrapped into its own context with (function () { /* your script here */ })();,
so global variables must be assigned to window instead of implicitly declared.
Note that calling this function multiple times overrides previous values.
This is executed only on the main frame.
If you only want to run it in all frames, use Self::js_init_script_on_all_frames instead.
§Platform-specific
- Windows: scripts are always added to subframes.
- Android: When addDocumentStartJavaScript is not supported, we prepend initialization scripts 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.
§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)
.build()
}Sourcepub fn js_init_script_on_all_frames(
self,
js_init_script: impl Into<String>,
) -> Self
pub fn js_init_script_on_all_frames( self, js_init_script: impl Into<String>, ) -> Self
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.
Note that calling this function multiple times overrides previous values.
This is executed on all frames, main frame and also sub frames.
If you only want to run it in the main frame, use Self::js_init_script instead.
§Platform-specific
- Windows: scripts are always added to subframes.
- Android: When addDocumentStartJavaScript is not supported, we prepend initialization scripts 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.
Sourcepub fn setup<F>(self, setup: F) -> Self
pub fn setup<F>(self, setup: F) -> Self
Define a closure that runs when the plugin is registered.
§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, api| {
app.manage(PluginState::default());
Ok(())
})
.build()
}Callback invoked when the webview tries to navigate to a URL. Returning false cancels the navigation.
#Example
use tauri::{plugin::{Builder, TauriPlugin}, Runtime};
fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("example")
.on_navigation(|webview, url| {
// allow the production URL or localhost on dev
url.scheme() == "tauri" || (cfg!(dev) && url.host_str() == Some("localhost"))
})
.build()
}Sourcepub fn on_page_load<F>(self, on_page_load: F) -> Self
pub fn on_page_load<F>(self, on_page_load: F) -> Self
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(|webview, payload| {
println!("{:?} URL {} in webview {}", payload.event(), payload.url(), webview.label());
})
.build()
}Sourcepub fn on_window_ready<F>(self, on_window_ready: F) -> Self
pub fn on_window_ready<F>(self, on_window_ready: F) -> Self
Callback invoked when the window is created.
§Examples
use tauri::{plugin::{Builder, TauriPlugin}, Runtime};
fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("example")
.on_window_ready(|window| {
println!("created window {}", window.label());
})
.build()
}Sourcepub fn on_webview_ready<F>(self, on_webview_ready: F) -> Self
pub fn on_webview_ready<F>(self, on_webview_ready: F) -> Self
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(|webview| {
println!("created webview {}", webview.label());
})
.build()
}Sourcepub fn on_event<F>(self, on_event: F) -> Self
pub fn on_event<F>(self, on_event: F) -> Self
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()
}Sourcepub fn on_drop<F>(self, on_drop: F) -> Self
pub fn on_drop<F>(self, on_drop: F) -> Self
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()
}Sourcepub fn register_uri_scheme_protocol<N: Into<String>, T: Into<Cow<'static, [u8]>>, H: Fn(UriSchemeContext<'_, R>, Request<Vec<u8>>) -> Response<T> + Send + Sync + 'static>(
self,
uri_scheme: N,
protocol_handler: H,
) -> Self
pub fn register_uri_scheme_protocol<N: Into<String>, T: Into<Cow<'static, [u8]>>, H: Fn(UriSchemeContext<'_, R>, Request<Vec<u8>>) -> Response<T> + Send + Sync + 'static>( self, uri_scheme: N, protocol_handler: H, ) -> Self
Registers a URI scheme protocol available to all webviews.
Leverages setURLSchemeHandler on macOS, AddWebResourceRequestedFilter on Windows and webkit-web-context-register-uri-scheme on Linux.
§Known limitations
URI scheme protocols are registered when the webview is created. Due to this limitation, if the plugin is registered after a webview has been created, this protocol won’t be available.
§Arguments
uri_schemeThe URI scheme to register, such asexample.protocolthe protocol associated with the given URI scheme. It’s a function that takes an URL such asexample://localhost/asset.css.
§Examples
use tauri::{plugin::{Builder, TauriPlugin}, Runtime};
fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("myplugin")
.register_uri_scheme_protocol("myscheme", |_ctx, req| {
http::Response::builder().body(Vec::new()).unwrap()
})
.build()
}§Warning
Pages loaded from a custom protocol will have a different Origin on different platforms.
Servers which enforce CORS will need to add the exact same Origin header (or *) 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>://localhost/<path>(so it will be `my-scheme://localhost/path/to/page). - Windows and Android:
http://<scheme_name>.localhost/<path>by default (so it will behttp://my-scheme.localhost/path/to/page). To usehttpsinstead ofhttp, usesuper::webview::WebviewBuilder::use_https_scheme.
Sourcepub fn register_asynchronous_uri_scheme_protocol<N: Into<String>, H: Fn(UriSchemeContext<'_, R>, Request<Vec<u8>>, UriSchemeResponder) + Send + Sync + 'static>(
self,
uri_scheme: N,
protocol_handler: H,
) -> Self
pub fn register_asynchronous_uri_scheme_protocol<N: Into<String>, H: Fn(UriSchemeContext<'_, R>, Request<Vec<u8>>, UriSchemeResponder) + Send + Sync + 'static>( self, uri_scheme: N, protocol_handler: H, ) -> Self
Similar to Self::register_uri_scheme_protocol but with an asynchronous responder that allows you
to process the request in a separate thread and respond asynchronously.
§Arguments
uri_schemeThe URI scheme to register, such asexample.protocolthe protocol associated with the given URI scheme. It’s a function that takes an URL such asexample://localhost/asset.css.
§Examples
use tauri::{plugin::{Builder, TauriPlugin}, Runtime};
fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("myplugin")
.register_asynchronous_uri_scheme_protocol("app-files", |_ctx, request, responder| {
// skip leading `/`
let path = request.uri().path()[1..].to_string();
std::thread::spawn(move || {
if let Ok(data) = std::fs::read(path) {
responder.respond(
http::Response::builder()
.body(data)
.unwrap()
);
} else {
responder.respond(
http::Response::builder()
.status(http::StatusCode::BAD_REQUEST)
.header(http::header::CONTENT_TYPE, mime::TEXT_PLAIN.essence_str())
.body("failed to read file".as_bytes().to_vec())
.unwrap()
);
}
});
})
.build()
}§Warning
Pages loaded from a custom protocol will have a different Origin on different platforms.
Servers which enforce CORS will need to add the exact same Origin header (or *) 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>://localhost/<path>(so it will be `my-scheme://localhost/path/to/page). - Windows and Android:
http://<scheme_name>.localhost/<path>by default (so it will behttp://my-scheme.localhost/path/to/page). To usehttpsinstead ofhttp, usesuper::webview::WebviewBuilder::use_https_scheme.
Sourcepub fn try_build(self) -> Result<TauriPlugin<R, C>, BuilderError>
pub fn try_build(self) -> Result<TauriPlugin<R, C>, BuilderError>
Builds the TauriPlugin.
Sourcepub fn build(self) -> TauriPlugin<R, C>
pub fn build(self) -> TauriPlugin<R, C>
Builds the TauriPlugin.
§Panics
If the builder returns an error during Self::try_build, then this method will panic.