Notification:permission 静态属性

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

安全上下文: 此功能仅在安全上下文(HTTPS)中可用,且支持此功能的浏览器数量有限。

注意:此功能在 Web Workers 中可用。

Notification 接口中只读的 permission 静态属性指示当前用户为当前源授予的用于显示 Web 通知的状态。

一个表示当前权限的字符串。该值可以是:

granted

用户已明确授予当前源显示系统通知的权限。

denied

用户已明确拒绝当前源显示系统通知的权限。

default

用户决定未知;在这种情况下,应用程序将如同权限被denied(拒绝)一样处理。

示例

如果您想在发送通知之前,先检查是否支持通知,然后检查当前源是否已授予发送通知的权限,如果需要则请求权限,可以使用以下代码片段。

js
function notifyMe() {
  if (!("Notification" in window)) {
    // Check if the browser supports notifications
    alert("This browser does not support desktop notification");
  } else if (Notification.permission === "granted") {
    // Check whether notification permissions have already been granted;
    // if so, create a notification
    const notification = new Notification("Hi there!");
    // …
  } else if (Notification.permission !== "denied") {
    // We need to ask the user for permission
    Notification.requestPermission().then((permission) => {
      // If the user accepts, let's create a notification
      if (permission === "granted") {
        const notification = new Notification("Hi there!");
        // …
      }
    });
  }

  // At last, if the user has denied notifications, and you
  // want to be respectful there is no need to bother them anymore.
}

规范

规范
Notifications API
# dom-notification-permission

浏览器兼容性

另见