首页 > 解决方案 > 获得 chrome 通知的权限

问题描述

我正在尝试从我的用户那里获得这样的通知许可

在此处输入图像描述

但是,此代码不会发送权限请求

function notifyMe() {
  // Let's check if the browser supports notifications
  if (!("Notification" in window)) {
    alert("This browser does not support desktop notification");
  }

  // Let's check if the user is okay to get some notification
  else if (Notification.permission === "granted") {
    // If it's okay let's create a notification
    var notification = new Notification("Hi there!");
  }

  // Otherwise, we need to ask the user for permission
  // Note, Chrome does not implement the permission static property
  // So we have to check for NOT 'denied' instead of 'default'
  else if (Notification.permission !== 'denied') {
    Notification.requestPermission(function (permission) {

      // Whatever the user answers, we make sure we store the information
      if(!('permission' in Notification)) {
        Notification.permission = permission;
      }

      // If the user is okay, let's create a notification
      if (permission === "granted") {
        var notification = new Notification("Hi there!");
      }
    });
  } else {
    alert(`Permission is ${Notification.permission}`);
  }
}

只是说“权限被拒绝”

是因为我使用的是codepen吗?

标签: google-chrome

解决方案


这不是因为您使用 CodePen - 不是直接使用。这是因为您试图从跨域 iframe 请求通知权限,而 Chrome 和 Firefox(可能还有其他浏览器)不允许这样做,如文档中所述

我们不再在此页面上显示实时示例,因为 Chrome 和 Firefox 不再允许从跨域 <iframe> 请求通知权限,而其他浏览器将跟随。

为了证明它是一个跨域浏览器,你可以在开发工具中看到srcCodePen 上的 iframe 的属性指向,https://cdpn.io/并且 iframe 本身是嵌入到https://codepen.io/域中的——这就是一个跨域 iframe。

要使其在 CodePen 上运行,您可以尝试这样。它基本上省略了Notification.permission !== 'denied'检查。

但总的来说,您的代码在真实浏览器中可以正常工作。您可以通过在浏览器的控制台中粘贴您的函数然后运行它来确认这一点。


推荐阅读