Cargo.toml中添加依赖
tauri-plugin-autostart = { git = "<https://github.com/tauri-apps/plugins-workspace>", branch = "v1" }
main.rs添加插件tauri-plugin-autostart
#![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
use tauri::{CustomMenuItem, SystemTray, SystemTrayEvent, SystemTrayMenu};
**use tauri_plugin_autostart::MacosLauncher;**
fn main() {
let opt_quit = CustomMenuItem::new("quit", "Quit");
let tray_menu = SystemTrayMenu::new().add_item(opt_quit);
let system_tray = SystemTray::new().with_menu(tray_menu);
tauri::Builder::default()
**.plugin(tauri_plugin_autostart::init(
MacosLauncher::LaunchAgent,
None,
))**
.system_tray(system_tray)
.on_system_tray_event(|_app, event| match event {
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
"quit" => std::process::exit(0),
_ => {}
},
_ => {}
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
添加js依赖tauri-plugin-autostart-api
pnpm add <https://github.com/tauri-apps/tauri-plugin-autostart#v1>
页面引用控制
import { enable, isEnabled, disable } from "tauri-plugin-autostart-api";
const handleAutoStart = async () => {
try {
const isAutoStart = await isEnabled();
console.log("是否配置了开机自启:", isAutoStart);
if (!isAutoStart) {
await enable();
}
} catch (error) {
console.log("handleAutoStart ~ error:", error);
}
};