添加依赖:
notify-rust = "4.11.7"
添加一个command给前端调用:
use notify_rust::Notification;
#[derive(serde::Deserialize)]
pub struct NotificationParams {
title: String,
body: String,
icon: String,
}
#[tauri::command]
pub fn notification(app: AppHandle, params: NotificationParams) -> Result<(), String> {
let mut notifi_app = Notification::new();
#[cfg(target_os = "macos")]
{
let _ = notify_rust::set_application(if tauri::is_dev() {
"com.apple.Terminal"
} else {
&app.config().identifier
});
}
#[cfg(windows)]
{
use std::path::MAIN_SEPARATOR as SEP;
let curr_dir = get_exe_dir(true);
// set the notification's System.AppUserModel.ID only when running the installed app
if !(curr_dir.ends_with(format!("{SEP}target{SEP}debug").as_str())
|| curr_dir.ends_with(format!("{SEP}target{SEP}release").as_str()))
{
notifi_app.app_id(&app.config().identifier);
}
}
if !params.icon.is_empty() {
notifi_app.icon(¶ms.icon);
} else {
notifi_app.auto_icon();
}
tauri::async_runtime::spawn(async move {
let _ = notifi_app
.summary(¶ms.title)
.body(¶ms.body)
.show()
.expect("show notification failed");
});
Ok(())
}
前端调用:
invoke('notification', {
params: {
title: t('notificationTitle'),
body: textarea.value,
icon: 'face-smile',
},
})
然后就可以发送通知了: