9

我正在尝试在页面加载时使用 jQuery 在本地显示通知。通知在 Firefox、Firefox Developer 和 Chrome 中正确显示。尽管通知首选项设置允许,但通知未出现在 Safari 中。

MDN 站点https://developer.mozilla.org/en/docs/Web/API/notification也有类似的代码。

片段如下。

// Display a sample notification
  if (window.Notification) {
    return $(".au-notifications-page").show(function() {
      var notification;
      notification = new Notification(
        'Success Text', {
        //tag: $("[name=tag]").val(),
        body: 'Success Message',
        iconUrl: 'img/avatar-male.png',
        icon: 'img/avatar-male.png'
      });
      return notification.onclick = function() {
        notification.close();
        window.open().close();
        return window.focus();
      };
    });
  };

完整代码如下。

$(document).ready(function () {

  // Request permission on site load
  Notification.requestPermission().then(function(result) {
    if (result === 'denied') {
      //alert('denied');
      $(".au-notif-disabled-header").removeClass('hide');
      $(".au-notif-disabled-header .btn").addClass('hide');
      return;
    }
    if (result === 'default') {
      //alert('ignored');
      $(".au-notif-disabled-header").removeClass('hide');
      return;
    }
    //alert('granted');
    $(".au-notif-disabled-header").addClass('hide');
  });

  // Request permission with button
  $('.au-notif-disabled-header .btn').click(function () {
    Notification.requestPermission().then(function(result) {
      if (result === 'denied') {
        $(".au-notif-disabled-header").removeClass('hide');
        $(".au-notif-disabled-header .btn").addClass('hide');
        return;
      }
      if (result === 'default') {
        $(".au-notif-disabled-header").removeClass('hide');
        return;
      }
      $(".au-notif-disabled-header").addClass('hide');
    });
  });

  $( ".au-notification-icon" ).hover(
    function() {
      $(".au-notifications-menu .au-notif-msg-realtime").slideDown();
      $('.au-notification-icon .badge').html("2");
    }, function() {
      $(".au-notifications-menu .au-notif-msg-realtime").slideUp();
      $('.au-notification-icon .badge').html("1");
    }
  );

  //To show notification received while on notifications page
  $(".au-notif-msg-realtime").hide();
  //$(".au-notifications-page .au-notif-msg-realtime").slideDown();

  $(".au-notifications-page .au-notif-msg-realtime").slideDown({
    complete: function(){
      $('.au-notification-icon .badge').html("2");
      $('head title').html("(2) Notifications");
    }
  });


  // Display a sample notification
  if (window.Notification) {
    return $(".au-notifications-page").show(function() {
      var notification;
      notification = new Notification(
        'Success Heading', {
          body: 'Success Text',
          iconUrl: 'img/avatar-male.png',
          icon: 'img/avatar-male.png'
      });
      return notification.onclick = function() {
        notification.close();
        window.open().close();
        return window.focus();
      };
    });
  };
});

编辑 1:Safari 抛出此异常

undefined 不是对象(评估 'Notification.requestPermission().then')

4

3 回答 3

18

您必须为 Safari 使用回调函数,因为它不返回 Promise。

根据MDN

这使用了该方法的 promise-version,正如最近的实现(例如 Firefox 47)所支持的那样。如果你想支持旧版本,你可能必须使用旧的回调版本,它看起来像这样:

这是他们提供的示例代码:

Notification.requestPermission(function (permission) {
    // If the user accepts, let's create a notification
    if (permission === "granted") {
        var notification = new Notification("Hi there!");
    }
});

为了支持 Safari 通知,我最终得到了这样的结果:

    try {
        Notification.requestPermission()
            .then(() => doSomething())                                                                                                                                               
    } catch (error) {
        // Safari doesn't return a promise for requestPermissions and it                                                                                                                                       
        // throws a TypeError. It takes a callback as the first argument                                                                                                                                       
        // instead.
        if (error instanceof TypeError) {
            Notification.requestPermission(() => {                                                                                                                                                             
                doSomething();
            });
        } else {
            throw error;                                                                                                                                                                                       
        }                                                                                                                                                                                                      
    }      
于 2016-09-02T00:03:39.993 回答
11

更好的解决方案是将结果包装在 a 中Promise然后(没有双关语)运行您的代码。此代码适用于所有浏览器(包括 Safari)并且没有复杂的块(此问题if中详细讨论了概念)

Promise.resolve(Notification.requestPermission()).then(function(permission) {
    // Do something
});

这是有效的,因为Promise.resolve对 a 没有任何作用Promise,但会将 Safari 转换requestPermission()为 a Promise

请注意,iOS Safari 仍然不支持 Notification API,因此您需要先检查它是否可用

于 2019-12-19T20:54:51.867 回答
1

要返回在用户授予或拒绝显示通知的权限之前不会解决的承诺:

        if (!permissionPromise && Notification.permission === 'granted' ) {
            permissionPromise = Promise.resolve(Notification.permission);
        }
        if (!permissionPromise) {
            permissionPromise = new Promise(function (resolve, reject) {
                // Safari uses callback, everything else uses a promise
                var maybePromise = $window.Notification.requestPermission(resolve, reject);
                if (maybePromise && maybePromise.then) {
                    resolve(maybePromise);
                }
            });
        }
        return permissionPromise;
于 2021-02-09T20:18:54.307 回答