Skip to main content

tauri_plugin_cef_webview/
lib.rs

1//! Embed native child webviews in a Tauri application and control them from
2//! the frontend with a plain `<webview>` element.
3
4mod commands;
5mod registry;
6mod scripts;
7
8pub use registry::{CefWebview, Registry};
9
10use tauri::{
11    plugin::{Builder as PluginBuilder, TauriPlugin},
12    Manager, Runtime,
13};
14
15/// Installed into every application page so `<webview>` works without imports.
16/// Registered as a plugin initialization script, so it runs before any page
17/// script in every webview, including windows created from the app config.
18const HOST_RUNTIME: &str = include_str!("element.js.inc");
19
20/// Plugin configuration.
21#[derive(Clone, Debug, Default)]
22pub struct Config {
23    /// JavaScript injected into every child webview before page scripts run.
24    pub js: Vec<String>,
25    /// CSS injected into every child webview.
26    pub css: Vec<String>,
27}
28
29impl Config {
30    /// Adds a JavaScript snippet applied to every child webview.
31    pub fn js(mut self, script: impl Into<String>) -> Self {
32        self.js.push(script.into());
33        self
34    }
35
36    /// Adds a stylesheet applied to every child webview.
37    pub fn css(mut self, css: impl Into<String>) -> Self {
38        self.css.push(css.into());
39        self
40    }
41}
42
43/// Initializes the plugin with the default configuration.
44pub fn init<R: Runtime>() -> TauriPlugin<R> {
45    init_with(Config::default())
46}
47
48/// Initializes the plugin with a custom configuration.
49pub fn init_with<R: Runtime>(config: Config) -> TauriPlugin<R> {
50    PluginBuilder::new("cef-webview")
51        .initialization_script(HOST_RUNTIME)
52        .invoke_handler(tauri::generate_handler![
53            commands::create,
54            commands::set_rect,
55            commands::set_visible,
56            commands::destroy,
57            commands::eval,
58            commands::insert_css,
59            commands::remove_inserted_css,
60            commands::navigate,
61            commands::reload,
62            commands::open_devtools,
63            commands::call,
64        ])
65        .setup(move |app, _api| {
66            app.manage(Registry::<R>::new(config));
67            Ok(())
68        })
69        .build()
70}
71
72/// Access the plugin registry from a Tauri app handle.
73pub trait CefWebviewExt<R: Runtime> {
74    /// Returns the plugin registry, which exposes [`Registry::get`].
75    fn cef_webviews(&self) -> tauri::State<'_, Registry<R>>;
76}
77
78impl<R: Runtime, M: Manager<R>> CefWebviewExt<R> for M {
79    fn cef_webviews(&self) -> tauri::State<'_, Registry<R>> {
80        self.state::<Registry<R>>()
81    }
82}