14

アプリにWebKit 通知を使用しています。このコードを使用している場合は、次のように言います。

var n = window.webkitNotifications.createNotification(
   'icon.png',
   'New Comment',
   'Praveen commented on your post!'
);
n.onclick = function(x) { window.focus(); this.cancel(); };
n.show();

PS 1:最初の 5 行は実際には 1 行です。読みやすくするために、このように投稿しました。

PS 2:完全なコードについては、こちらを参照してください: Unable to show Desktop Notifications using Google Chrome .

私の質問は、複数のタブを開いている場合はどうすればよいですか?

アプリに新しいコメントが表示されたときに、これが起動されるかどうかを考えてみましょう。複数のタブを開いている場合はどうなりますか? これにより多くの通知が生成されますか? たとえば、10 - 15タブを開いていると、2 つの通知が表示されます。生成される通知の数は20 - 30?

その場合、開いているタブごとに単一の通知が複数回生成されるのを防ぐ方法は?

4

2 に答える 2

25

通知には「タグ」オプションを指定するだけです。タグに同じ値を持つ通知は、多くのタブが開いていても 1 回しか表示されません。

例えば:

var notification = new Notification('Hey!', {
    body : 'So nice to hear from you',
    tag : 'greeting-notify',
    icon : 'https://mysite.com/my_funny_icon.png'
});
于 2013-06-26T07:30:52.917 に答える
8

最後の通知のみが表示されるようにタグ付けする通知の詳細な説明は 、MDN ドキュメント サイトで入手できます。

コードの抜粋 [ドキュメントがダウンした場合に備えて]

HTML

<button>Notify me!</button>

JS

window.addEventListener('load', function () {
  // At first, let's check if we have permission for notification
  // If not, let's ask for it
  if (Notification && Notification.permission !== "granted") {
    Notification.requestPermission(function (status) {
      if (Notification.permission !== status) {
        Notification.permission = status;
      }
    });
  }

  var button = document.getElementsByTagName('button')[0];

  button.addEventListener('click', function () {
    // If the user agreed to get notified
    // Let's try to send ten notifications
    if (Notification && Notification.permission === "granted") {
      for (var i = 0; i < 10; i++) {
        // Thanks to the tag, we should only see the "Hi! 9" notification
        var n = new Notification("Hi! " + i, {tag: 'soManyNotification'});
      }
    }

    // If the user hasn't told if he wants to be notified or not
    // Note: because of Chrome, we are not sure the permission property
    // is set, therefore it's unsafe to check for the "default" value.
    else if (Notification && Notification.permission !== "denied") {
      Notification.requestPermission(function (status) {
        if (Notification.permission !== status) {
          Notification.permission = status;
        }

        // If the user said okay
        if (status === "granted") {
          for (var i = 0; i < 10; i++) {
            // Thanks to the tag, we should only see the "Hi! 9" notification
            var n = new Notification("Hi! " + i, {tag: 'soManyNotification'});
          }
        }

        // Otherwise, we can fallback to a regular modal alert
        else {
          alert("Hi!");
        }
      });
    }

    // If the user refuses to get notified
    else {
      // We can fallback to a regular modal alert
      alert("Hi!");
    }
  });
});
于 2014-04-14T16:28:43.260 に答える