首页 / Tauri 2 入门教程 / 系统通知

Tauri 2 入门教程

系统通知

本教程共 48 篇 · 第 36 篇 · 更新于 2026-08-09 · 约 7 分钟阅读

TauriTauri 2 入门教程plugin-notification系统通知notification消息推送

本节目标:读完你能用 plugin-notification 在 Tauri 应用中发送原生系统通知,理解权限请求流程,并知道如何用频道(channel)组织不同类型的通知。

桌面应用经常需要用系统通知(notification)来提醒用户——下载完成、新消息、定时任务执行完毕等。Tauri 的 tauri-plugin-notification 让你在前端 JS 或 Rust 端发送原生通知,还能设置标题、正文、图标,甚至附带附件和交互按钮。

安装与注册通知插件

安装过程不变:

# 1. Rust 端
cd src-tauri
cargo add tauri-plugin-notification
// 2. 注册插件
// src-tauri/src/lib.rs
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_notification::init())
        .run(tauri::generate_context!())
        .expect("运行 Tauri 应用时出错");
}
# 3. 前端
npm install @tauri-apps/plugin-notification

权限方面,通知插件支持移动端和桌面端。在 src-tauri/capabilities/default.json 里加入:

{
  "permissions": [
    "core:default",
    "notification:default"
  ]
}

notification:default 包含了发送通知的基本权限。如果你只需要部分功能,可以用更细粒度的权限,比如 notification:allow-notify 只允许发送通知,notification:allow-request-permission 允许请求权限。

发送通知的前提:检查并请求权限

在 macOS 和 Windows 上,应用第一次发通知前需要用户授权。流程是:先检查有没有权限,没有的话请求一次,拿到权限再发。

import {
  isPermissionGranted,
  requestPermission,
  sendNotification,
} from "@tauri-apps/plugin-notification";

// 1. 检查是否已获得权限
let permissionGranted = await isPermissionGranted();

// 2. 没有权限就请求
if (!permissionGranted) {
  const permission = await requestPermission();
  permissionGranted = permission === "granted";
}

// 3. 有权限了,发通知
if (permissionGranted) {
  sendNotification({
    title: "Tauri",
    body: "Tauri is awesome!",
  });
}

isPermissionGranted 返回一个布尔值,表示当前是否已获得通知权限。requestPermission 会弹出系统对话框让用户选择,返回 "granted"(允许)、"denied"(拒绝)或 "default"(未决定)。只有用户允许后,通知才能真正显示出来。

Note

Windows 上首次运行时,系统会弹出一个对话框问用户是否允许此应用发送通知。macOS 上类似,用户可以在「系统设置 → 通知」里管理每个应用的通知权限。如果用户拒绝了,requestPermission 不会再次弹窗——你只能引导用户去系统设置里手动开。

发送通知:标题、正文与更多选项

sendNotification 接受一个对象,最基本的字段是 titlebody

sendNotification({
  title: "下载完成",
  body: "文件已保存到 Downloads 文件夹",
});

你还可以设置图标、声音等。通知对象支持的常用字段:

sendNotification({
  title: "新消息",
  body: "你有一条未读消息",
  icon: "icon.png",      // 图标文件路径
  sound: "default",      // 播放默认通知音
});

sendNotification 是同步调用的——它不会返回 Promise,调用后通知立刻发出。如果你想确保通知构建无误,可以先构建再发送,但大多数场景直接调 sendNotification 就够了。

Rust 端发送通知

Rust 端用 NotificationExt trait,通过 app.notification() 获取构建器:

use tauri_plugin_notification::NotificationExt;

tauri::Builder::default()
    .plugin(tauri_plugin_notification::init())
    .setup(|app| {
        app.notification()
            .builder()
            .title("Tauri")
            .body("Tauri is awesome")
            .show()
            .unwrap();
        Ok(())
    })
    .run(tauri::generate_context!())
    .expect("运行 Tauri 应用时出错");

.builder() 创建一个通知构建器,链式调用 .title().body() 设置内容,最后 .show() 发出通知。Rust 端不需要手动检查权限——如果没权限,.show() 会静默失败或返回错误,不会崩溃。

Tip

Rust 端发通知不依赖前端,适合在后台任务里用。比如文件下载完成、定时任务触发等场景,在 Rust 命令里直接发通知,不需要走前端。

频道:给通知分类

频道(channel)是 Android 通知系统的一个重要概念——Android 8.0 以上要求每条通知必须属于一个频道,用户可以针对每个频道单独设置响铃、震动等行为。Tauri 的通知插件封装了频道 API,让你在所有平台上用一致的接口管理通知分类。

先创建一个频道:

import {
  createChannel,
  Importance,
  Visibility,
} from "@tauri-apps/plugin-notification";

await createChannel({
  id: "messages",
  name: "消息通知",
  description: "新消息到达时通知",
  importance: Importance.High,
  visibility: Visibility.Private,
  lights: true,
  lightColor: "#ff0000",
  vibration: true,
  sound: "notification_sound",
});

频道属性说明:

  • id: 频道唯一标识,发通知时用这个 id 指定频道。
  • name: 用户可见的频道名称(Android 设置里会显示)。
  • importance: 优先级,从低到高有 NoneMinLowDefaultHighHigh 会弹出悬浮通知。
  • visibility: 锁屏可见性:Secret(隐藏)、Private(显示但隐藏内容)、Public(完全显示)。
  • lights / lightColor: 通知 LED 灯(部分 Android 设备)。
  • vibration: 是否震动。
  • sound: 自定义通知音文件名。

创建好频道后,发通知时指定 channelId

sendNotification({
  title: "新消息",
  body: "你有一条未读消息",
  channelId: "messages",
});
Note

频道主要在 Android 上生效。在 Windows 和 macOS 上,channelId 会被忽略——这些平台没有频道的概念,所有通知统一管理。但使用频道 API 不会报错,只是行为不同。建议还是用频道,这样你的应用在 Android 上表现更好。

管理已有频道的方法:

import { channels, removeChannel } from "@tauri-apps/plugin-notification";

// 列出所有已创建的频道
const list = await channels();
console.log(list);

// 删除一个频道
await removeChannel("messages");
Warning

在 Android 上,频道一旦创建就不能改 importance——用户会看到你最初设定的优先级,之后只能在系统设置里由用户自己调低。所以创建频道时优先级别定太高,Default 通常就够了,真正紧急的才用 High

附件:给通知加图片

通知还可以附带文件附件(attachment),比如一张图片。这在展示截图预览、接收图片消息等场景很实用:

sendNotification({
  title: "新图片",
  body: "查看这张图片",
  attachments: [
    {
      id: "image-1",
      url: "asset:///notification-image.jpg",
    },
  ],
});

url 支持 asset:// 协议(应用内置资源)和 file:// 协议(本地文件)。附件支持因平台而异,建议在目标平台上测试确认效果。

通知交互行为(移动端)

通知插件还支持在通知上添加交互按钮(Actions),比如「回复」「标记已读」等。不过这个功能目前只在移动端可用:

import { registerActionTypes } from "@tauri-apps/plugin-notification";

await registerActionTypes([
  {
    id: "messages",
    actions: [
      {
        id: "reply",
        title: "回复",
        input: true,
        inputButtonTitle: "发送",
        inputPlaceholder: "输入回复内容...",
      },
      {
        id: "mark-read",
        title: "标记已读",
        foreground: false,
      },
    ],
  },
]);

每个 action 可以设置 input: true 来添加文本输入框(适合快捷回复),foreground: false 表示点击后不把应用拉到前台(后台处理)。监听用户点击 action 的事件用 onAction

import { onAction } from "@tauri-apps/plugin-notification";

await onAction((notification) => {
  console.log("用户点击了通知按钮:", notification);
});
Note

Actions API 标记为「Mobile Only」,在桌面端不生效。如果你的应用同时面向桌面和移动端,需要在桌面端做降级处理——桌面端通知只展示标题和正文,不支持交互按钮。

小结

tauri-plugin-notification 让 Tauri 应用能发送原生系统通知。发送前需用 isPermissionGranted 检查权限、requestPermission 请求权限,然后 sendNotification({ title, body }) 一行发出。Rust 端用 NotificationExt.builder().title().body().show() 链式调用。频道(channel)是 Android 特有的通知分类机制,用 createChannel 创建,发通知时指定 channelId,让用户可以按类别管理通知行为。附件(attachment)可以给通知加图片,交互按钮(Actions)目前仅移动端可用。通知插件在桌面和移动端都支持,但部分高级功能(Actions、频道行为)有平台差异,使用时注意测试目标平台。