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

瀏覽器相容性

另見