この記事の目的
Node.js経由でWindows10 のプログレスバー付のトースト表示を表示させる。
前提条件
以下のモジュールがインストールされていることを前提とします。
- @nodert-win10-rs4/windows.ui.notifications
- @nodert-win10-rs4/windows.data.xml.dom
今回はnodert-win10-rs4でテストしていますが、nodert-win10-20h1
など、別のバージョンでも動くと思います。
NodeRTのインストールは一筋縄では行かないことがありますが、他のQiita記事等を参照することで解決できます。
コード
トーストの作成
const xml = require("@nodert-win10-rs4/windows.data.xml.dom");
const {
ToastNotification,
ToastNotificationManager,
NotificationData,
} = require("@nodert-win10-rs4/windows.ui.notifications");
/* トーストのXML 参照: https://docs.microsoft.com/en-us/uwp/schemas/tiles/toastschema/schema-root */
const msgTemplate = `<toast>
<visual>
<binding template="ToastGeneric">
<text>通知テスト</text>
<progress value="{progressValue}" valueStringOverride="{progressValueString}" status="{progressStatus}"/>
</binding>
</visual>
</toast>`;
/* アプリケーションID */
const appId =
"{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe";
/* トーストのTag, Group */
let tag = "tag";
let group = "group";
let toastXml = new xml.XmlDocument();
toastXml.loadXml(msgTemplate);
let toast = new ToastNotification(toastXml);
toast.tag = tag;
toast.group = group;
/* 作成したトーストのイベント */
toast.on("activated", function (sender, eventArgs) {
// onActiviation();
});
toast.on("dismissed", function () {
// onDismissal();
});
/* プログレスバーの設定*/
let d = {};
d["progressValue"] = 0.2;
d["progressValueString"] = "文字";
d["progressStatus"] = "ステータス";
toast.data = new NotificationData(d, 1);
/* トースト表示 */
ToastNotificationManager.createToastNotifier(appId).show(toast);
msgTemplate
はトーストの内容を定義するXMLです。XMLを変更すれば、画像やボタンを追加することができます。
https://docs.microsoft.com/en-us/uwp/schemas/tiles/toastschema/schema-rootなどを見ながらXMLを作成することができますが、Visual StudioでToastContentBuilder
を使ってトーストを作った後、GetXml()
でXMLを出力して貼り付けた方が早いかもしれません。
appId
は、アプリケーションユーザーモデル ID
を渡します。このIDは実際にWindows 10上にインストールされているアプリケーションのIDを渡さないと通知されないようです。
このIDはPowershellでget-AppxPackage
コマンドを実行すると取得できます。先に挙げたコード例では、PowershellのIDを設定しています。
トーストの更新
以下のコードを呼び出すことでトーストを更新することができます。
let d = {};
d["progressValue"] = 0.9;
d["progressValueString"] = "文字2";
d["progressStatus"] = "ステータス2";
ToastNotificationManager.createToastNotifier(appId).update(
new NotificationData(d, 2),
tag,
group
);
Electronでの通知
例えばElectronでは、OSで実装されている通知機能を用いて通知を作成することができます。実際に通知を行ってみると、Windows 10では以下のようなトースト表示が行われます。
しかし、これ以上に機能を拡張したトーストを表示することはできません。もしも画像やプログレスバーを付加したトーストを表示させたい場合は、今回のような方法で実現可能です。
ただし、 electron-rebuild
を用いて、トースト表示に必要なモジュールをリビルドする必要があります。