检测浏览器推送通知已启用并显示警报

Detect browser push notifications are enabled and display alert

我为我的网站启用了推送通知。当用户单击我网站上的 link 时,将向浏览器发送一个请求,用户必须单击允许或禁止。有没有办法检测通知是否已打开并显示 javascript 警告框,其中包含推送通知已成功启用的消息?这可能仅在用户允许 his/her 浏览器中的通知时显示。示例:

  1. The user clicks the link.
  2. The user clicks allow in his/her browser.
  3. There will be an alert with the message: "Successfully enabled"

另一个例子:

  1. The user clicks the link.
  2. The user clicks disallow in his/her browser.
  3. There will be an alert with the message: "Error with enabling"

有人懂我吗?如果还有更多问题,请发表评论,我会添加更多信息。谢谢你帮助我!

Notification.requestPermission() 是一个 Promise,它会根据用户选择的权限进行解析。

https://developer.mozilla.org/en-US/docs/Web/API/Notification/requestPermission

var myLink = document.getElementById("myLink");

myLink.addEventListener("click", function() {
   Notification.requestPermission().then(function(result) {
      if (result === 'denied' || result === 'default' ) {
        alert("Error with enabling");
        return;
      }
      alert("Succesfully enabled");
    });
});
<a id="myLink" href="#">Link</a>