早く流れる川で

雑に書き留めた何か

JavaScript, Notification APIを使ってトースト通知をする、その2

はじめに

前回のNotificationのインスタンスを作成した後のオブジェクトはどうするんだ?と気になったので調べた。

動作環境

開発環境

イベントを設定できる

    const title     = "Good day!";
    const options   = {
        body : "It's a wonderful day!?",
        icon : "../Image/Icon/onsen64.png"
    };

    const notification = new Notification(title, options);

    notification.onclick = function(event) {
        console.log("クリックしましたね!");
    };

    notification.onshow = function(event) {
        console.log("表示しましたね!");
    };

    notification.onclose = function(event) {
        console.log("閉じましたね!");
    };

    notification.onerror = function(event) {
        console.log("エラーです!");
    };

onerrorは動作未確認。
onclick内でthrow "sample"を実行したけど発火しなかった。

おまけ、クリックイベント時のtimestampを得る

    notification.onclick = function(event) {
        console.log(new Date(this.timestamp));
    };

最初はoptionsdataプロパティにnew Date()を仕込んでいたけど、
console.log(this);の表示を見ていたらtimestampプロパティの存在に気づいた。
一部のブラウザでは未対応なので注意が必要か。

おまけ、雑記

  • dirプロパティは指定してみたが変化なし
  • silentプロパティはtrueにしたら通知音が消えた

参考