Skip to main content

tauri_plugin_webdriver/
lib.rs

1use tauri::{
2    plugin::{Builder, TauriPlugin},
3    Manager, Runtime,
4};
5
6#[cfg(desktop)]
7mod desktop;
8#[cfg(mobile)]
9mod mobile;
10
11mod error;
12mod platform;
13mod server;
14mod webdriver;
15
16pub use error::{Error, Result};
17
18/// Default port for the `WebDriver` HTTP server
19pub const DEFAULT_PORT: u16 = 4445;
20
21/// Environment variable name for configuring the port
22pub const PORT_ENV_VAR: &str = "TAURI_WEBDRIVER_PORT";
23
24/// Initializes the plugin with default settings.
25///
26/// The port is determined in the following order:
27/// 1. `TAURI_WEBDRIVER_PORT` environment variable (if set and valid)
28/// 2. Default port (4445)
29#[must_use]
30pub fn init<R: Runtime>() -> TauriPlugin<R> {
31    let port = std::env::var(PORT_ENV_VAR)
32        .ok()
33        .and_then(|s| s.parse::<u16>().ok())
34        .unwrap_or(DEFAULT_PORT);
35
36    init_with_port(port)
37}
38
39/// Initializes the plugin with a custom port.
40///
41/// This ignores the `TAURI_WEBDRIVER_PORT` environment variable.
42#[must_use]
43pub fn init_with_port<R: Runtime>(port: u16) -> TauriPlugin<R> {
44    Builder::new("webdriver")
45        .setup(move |app, api| {
46            #[cfg(mobile)]
47            let webdriver = mobile::init(app, api)?;
48            #[cfg(desktop)]
49            let webdriver = desktop::init(app, api);
50            app.manage(webdriver);
51
52            // Manage async script state for native message handlers (Windows only)
53            #[cfg(target_os = "windows")]
54            app.manage(platform::AsyncScriptState::default());
55
56            // Manage per-window alert state
57            app.manage(platform::AlertStateManager::default());
58
59            // Start the WebDriver HTTP server
60            let app_handle = app.app_handle().clone();
61            server::start(app_handle, port);
62            tracing::info!("WebDriver plugin initialized on port {port}");
63
64            Ok(())
65        })
66        .on_webview_ready(|webview| {
67            platform::register_webview_handlers(&webview);
68        })
69        .build()
70}