【HTML5】Web Notifications API ~ 基本編 ~

■ はじめに

https://blogs.yahoo.co.jp/dk521123/37244153.html
の続き

Notificationあれこれ

【1】Web Notifications APIがサポートされているブラウザか確認
【2】指定した時間で通知を閉じる
【3】クリックイベントを拾う

【1】Web Notifications APIがサポートされているブラウザか確認

if ("Notification" in window) {
  // サポートされている
} else {
  // サポートされていない
}

サンプル

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Notification Demo</title>
</head>
<body>
  <button onclick="checkSupportOrNot()">Check</button><br />
</body>
<script type="text/javascript">
  function checkSupportOrNot() {
    if ("Notification" in window) {
      var notify = new Notification("Support!", {});
    } else {
      alert("Not Support!!");
    }
  }
</script>
</html>

参考文献

https://developer.mozilla.org/ja/docs/Web/API/notification

【2】指定した時間で通知を閉じる

setTimeout(function() {
  【Notificationインスタンス】.close();
}, 【時間】);

サンプル

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Notification Demo</title>
</head>
<body>
  <button onclick="sayHello()">Hi</button><br />
</body>
<script type="text/javascript">
  function sayHello() {
    if(window.Notification && Notification.permission !== "denied") {
      Notification.requestPermission(function(status) {
        var notify = new Notification(
          'Title ... Say Hello!', {
            body: 'Body ... Say World!!',
            icon: 'https://ident-001.west.edge.storage-yahoo.jp/res/ident-5mypszyrqsxdfvywx6dmdr5oam/profile/icon_sr?1274278682'
        });
  
        // ★3秒後消す★
        setTimeout(function() {
           notify.close();
        }, 3000);
      });
    }
  }
</script>
</html>

【3】クリックイベントを拾う

var 【Notificationsインスタンス】 = new Notification(
  // デスクトップ通知の内容
});

【Notificationsインスタンス】.onclick = function () {
  // クリック後のイベント処理
};

サンプル

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Notification Demo</title>
</head>
<body>
  <button onclick="sayHello()">Hi</button><br />
</body>
<script type="text/javascript">
  function sayHello() {
    if(window.Notification && Notification.permission !== "denied") {
      Notification.requestPermission(function(status) {
        var notify = new Notification(
          'Title ... Say Hello!', {
            body: 'Body ... Say World!!',
            icon: 'https://ident-001.west.edge.storage-yahoo.jp/res/ident-5mypszyrqsxdfvywx6dmdr5oam/profile/icon_sr?1274278682'
        });
  
        // ★Clickイベント★
        notify.onclick = function () {
          parent.focus();
          window.focus(); //just in case, older browsers
          alert("Say Hi!!");
          this.close();
        };
      });
    }
  }
</script>
</html>

参考文献

https://stackoverflow.com/questions/4906976/how-to-get-focus-to-a-chrome-tab-which-created-desktop-notification

関連記事

HTML5】Web Notifications API ~ 入門編 ~

https://blogs.yahoo.co.jp/dk521123/37244153.html