tauri项目发送系统通知notification以及遇到的问题

611 阅读1分钟

官方使用文档:Notifications | Tauri

安装

安装官方文档安装就好了

测试

如果是你自己的项目,直接在js中调用就好了,但是如果是通过注入js来实现的话,可以通过js来给windows默认的Notification修改为自己的通知

需要在rust端添加一个通知的command:


#[derive(serde::Deserialize)]
pub struct NotificationParams {
    title: String,
    body: String,
    icon: String,
}

#[tauri::command]
pub fn notification(app: AppHandle, params: NotificationParams) -> Result<(), String> {
    app.notification()
        .builder()
        .title(&params.title)
        .body(&params.body)
        .icon(&params.icon)
        .show()
        .unwrap();
    Ok(())
}

然后在js中修改通知:

document.addEventListener('DOMContentLoaded', function () {
  let permVal = 'granted';
  window.Notification = function (title, options) {
    const { invoke } = window.__TAURI__.core;
    const body = options?.body || '';
    let icon = options?.icon || '';

    // If the icon is a relative path, convert to full path using URI
    if (icon.startsWith('/')) {
      icon = window.location.origin + icon;
    }

    invoke('send_notification', {
      params: {
        title,
        body,
        icon,
      },
    });
  };

  window.Notification.requestPermission = async () => 'granted';

  Object.defineProperty(window.Notification, 'permission', {
    enumerable: true,
    get: () => permVal,
    set: v => {
      permVal = v;
    },
  });
});

发送的通知第一次有效,然后就失效了?

这个问题在github上也有遇到:github.com/tauri-apps/…

这是我遇到的最苦恼的问题,在测试环境中,第一次点击的时候,会出发点授权通知,但是第二次以后再点击通知,就没有任何反应了,其实是有通知的,打开你的通知栏,然后就可以看到你历史触发的消息都在这里了,包括开发环境下的通知

你需要做的是设置通知为总提示:

然后再次触发就有了:

window系统也可以: