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:前五行实际上是单行。只是为了可读性,我以这种方式发布。

PS 2:有关完整代码,请参阅:Unable to show Desktop Notifications using Google Chrome

我的问题是,如果我打开了多个标签怎么办?

说当我的应用程序上出现新评论时,这是否会被解雇。如果我打开了多个标签怎么办?这会产生很多通知吗?说,我10 - 15打开了标签,我收到了两个通知。将生成多少个通知,20 - 30

如果是这种情况,如何防止为每个打开的选项卡多次生成单个通知?

4

2 回答 2

25

您只需要指定通知的“标签”选项。即使打开了许多标签,标签中具有相同值的通知也只会显示一次。

例如:

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 回答