OS のネイティブ通知を送る

Recipe ID: dlg-009

OS 標準の通知センターやトースト通知機能を使用して、ユーザーにメッセージ(通知)を送る方法を紹介します。

前提条件

プラグインの追加

通知機能を利用するには notification プラグインが必要です。

npm run tauri add notification

src-tauri/src/lib.rs.plugin(tauri_plugin_notification::init()) が追加されていることを確認してください。

Permissions (権限) の設定

src-tauri/capabilities/default.jsonnotification:default 権限を追加します。

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

1. フロントエンドから作成する (TypeScript)

@tauri-apps/plugin-notificationsendNotification 関数を使用します。

基本的な通知の送信

最もシンプルな通知の送り方です。

import { sendNotification } from '@tauri-apps/plugin-notification';

sendNotification({
  title: '新しいお知らせ',
  body: 'バックグラウンド処理が完了しました。'
});

文字列のみでの送信

body のみを引数として渡すことも可能です。

import { sendNotification } from '@tauri-apps/plugin-notification';

sendNotification('処理が完了しました!');

通知許可の確認とリクエスト

最近の OS(特に macOS)では、アプリからの通知を表示するためにユーザーの許可が必要です。

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

async function notifyUser() {
  // 1. 現在の通知許可状態を確認
  let permissionGranted = await isPermissionGranted();

  // 2. 許可されていない場合、リクエストする
  if (!permissionGranted) {
    const permission = await requestPermission();
    permissionGranted = permission === 'granted';
  }

  // 3. 許可が得られたら通知を送信
  if (permissionGranted) {
    sendNotification({
      title: '許可ありがとうございます',
      body: 'これで重要な通知を受け取れます。'
    });
  }
}

2. バックエンドから作成する (Rust)

Rust 側から通知を送る場合は、コマンドを作成し NotificationExt トレイトを使用します。これによりフロントエンドから invoke で呼び出すことができます。

Rust からの通知送信

#[tauri::command]
fn notify_from_backend(app: tauri::AppHandle) {
    use tauri_plugin_notification::NotificationExt;

    app.notification()
        .builder()
        .title("Rust Notification")
        .body("This notification was sent from Rust backend!")
        .show()
        .expect("Failed to send notification");
}

// main関数などでハンドラを登録します
// .invoke_handler(tauri::generate_handler![notify_from_backend])

補足

  • OSネイティブ: Notification API を使用するため、Windows ならアクションセンター、macOS なら通知センターに履歴が残ります。
  • アイコン: デフォルトではアプリアイコンが通知に使用されます。Tauri の設定(tauri.conf.json)でアイコンが正しく設定されているか確認してください。