Webkit Notifications on Multiple Tabs

前端 未结 2 575
后悔当初
后悔当初 2020-12-16 00:30

I am using WebKit Notifications for my app. Say if I am using this code:

var n = window.webkitNotifications.createNotification(
   \'icon.pn         


        
相关标签:
2条回答
  • 2020-12-16 00:49

    A detailed explanation of Tagging notifications so only the last one appears is available on the MDN docs site

    An excerpt of the code [just in case the docs go down]

    The HTML

    <button>Notify me!</button>
    

    The 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!");
        }
      });
    });
    
    0 讨论(0)
  • 2020-12-16 01:05

    You just need to specify "tag" option for notification. Notifications with the same value in tag only shows once even if many tabs are opened.

    For example:

    var notification = new Notification('Hey!', {
        body : 'So nice to hear from you',
        tag : 'greeting-notify',
        icon : 'https://mysite.com/my_funny_icon.png'
    });
    
    0 讨论(0)
提交回复
热议问题