注入js脚本最常用的就是initialization_script,通过这个方法注入的js脚本在页面每个页面都会执行,这个在tauri文档也可以搜到:WebviewWindowBuilder in tauri::webview - Rust,但是请注意,这个方法只能用在WindowBuilder::new方法后面,不能在启动的时候用在main窗口里面。main窗口可以通过eval来实现注入一次性的js脚本,但是当页面切换或者刷新的时候,就不会再次执行了。
you can only use initialization_script if you create the window in rust (via WebviewWindowBuilder). If you want to keep the rest of the config in tauri.conf.json you can set create: false and use https://docs.rs/tauri/latest/tauri/webview/struct.WebviewWindowBuilder.html#method.from_config
如果是非常想在main页面加载js脚本,有一个变相的方式:
就是使用这种方式:
mod command;
use serde_json::json;
use tauri::{menu::*, WindowEvent};
use tauri_plugin_store::StoreExt;#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {tauri::Builder::default().menu(|handle| {let menu = Menu::with_items(handle,&[#[cfg(target_os = "macos")]&Submenu::with_items(handle,"Edit",true,&[&PredefinedMenuItem::undo(handle, None)?,&PredefinedMenuItem::redo(handle, None)?,&PredefinedMenuItem::cut(handle, None)?,&PredefinedMenuItem::copy(handle, None)?,&PredefinedMenuItem::paste(handle, None)?,&PredefinedMenuItem::select_all(handle, None)?,],)?,],);menu}).plugin(tauri_plugin_opener::init()).plugin(tauri_plugin_os::init()).plugin(tauri_plugin_fs::init()).plugin(tauri_plugin_shell::init()).plugin(tauri_plugin_dialog::init()).plugin(tauri_plugin_http::init()).plugin(tauri_plugin_clipboard_manager::init()).plugin(tauri_plugin_store::Builder::default().build()).setup(|app| {let app_handle = app.handle();let main_window = tauri::WebviewWindowBuilder::from_config(app_handle,&app.config().app.windows.get(0).unwrap().clone(),).unwrap().initialization_script(include_str!("./extension/event.js")).initialization_script(include_str!("./extension/custom.js")).build().unwrap();let store = app.store("app_data.json")?;let window_size: Option<serde_json::Value> = store.get("window_size");if let Some(window_size) = window_size {let size = window_size.as_object().unwrap();let width = size["width"].as_f64().unwrap();let height = size["height"].as_f64().unwrap();// println!("window size init: {:?}", size);main_window.set_size(tauri::PhysicalSize::new(width, height)).unwrap();}main_window.on_window_event(move |event| {if let WindowEvent::Resized(size) = event {// println!("window resized: {:?}", size);let _ = store.set("window_size",json!({"width": size.width,"height": size.height}),);}});Ok(())}).run(tauri::generate_context!()).expect("error while running tauri application");
}