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/// Plugin configuration.
16#[derive(Clone, Debug, Default)]
17pub struct Config {
18    /// JavaScript injected into every child webview before page scripts run.
19    pub js: Vec<String>,
20    /// CSS injected into every child webview.
21    pub css: Vec<String>,
22}
23
24impl Config {
25    /// Adds a JavaScript snippet applied to every child webview.
26    pub fn js(mut self, script: impl Into<String>) -> Self {
27        self.js.push(script.into());
28        self
29    }
30
31    /// Adds a stylesheet applied to every child webview.
32    pub fn css(mut self, css: impl Into<String>) -> Self {
33        self.css.push(css.into());
34        self
35    }
36}
37
38/// Initializes the plugin with the default configuration.
39pub fn init<R: Runtime>() -> TauriPlugin<R> {
40    init_with(Config::default())
41}
42
43/// Initializes the plugin with a custom configuration.
44pub fn init_with<R: Runtime>(config: Config) -> TauriPlugin<R> {
45    PluginBuilder::new("cef-webview")
46        .invoke_handler(tauri::generate_handler![
47            commands::create,
48            commands::set_rect,
49            commands::set_visible,
50            commands::destroy,
51            commands::eval,
52            commands::insert_css,
53            commands::remove_inserted_css,
54            commands::navigate,
55            commands::reload,
56            commands::open_devtools,
57        ])
58        .setup(move |app, _api| {
59            app.manage(Registry::<R>::new(config));
60            Ok(())
61        })
62        .build()
63}
64
65/// Access the plugin registry from a Tauri app handle.
66pub trait CefWebviewExt<R: Runtime> {
67    /// Returns the plugin registry, which exposes [`Registry::get`].
68    fn cef_webviews(&self) -> tauri::State<'_, Registry<R>>;
69}
70
71impl<R: Runtime, M: Manager<R>> CefWebviewExt<R> for M {
72    fn cef_webviews(&self) -> tauri::State<'_, Registry<R>> {
73        self.state::<Registry<R>>()
74    }
75}