Notification: requestPermission() 靜態方法
Notification 介面的 requestPermission() 靜態方法用於請求當前源顯示通知的許可權。
該方法返回一個 Promise,該 Promise 以一個字串解析,指示許可權是已授予還是已被拒絕。
語法
js
Notification.requestPermission()
// Deprecated syntax using a callback
Notification.requestPermission(callback)
引數
callback可選 已棄用-
一個可選的回撥函式,它會接收許可權值作為引數。已棄用,應優先使用
Promise的返回值。
返回值
一個 Promise,它解析為一個字串,表示使用者選擇的許可權。此字串的可能值為:
granted-
使用者已明確授予當前源顯示系統通知的許可權。
denied-
使用者已明確拒絕當前源顯示系統通知的許可權。
default-
使用者決定未知;在這種情況下,應用程式將像許可權被
denied一樣處理。
該方法的已棄用版本返回 undefined。
示例
假設以下基本 HTML
html
<button>Notify me!</button>
傳送通知的方法如下——這裡我們提供了一套相當冗長且完整的程式碼,您可以使用它來首先檢查通知是否受支援,然後檢查當前源是否已獲得傳送通知的許可權,如果需要則請求許可權,然後再發送通知。
請注意,請求應在響應使用者互動時發出:下面,該方法在 click 事件處理程式中呼叫。
js
document.querySelector("button").addEventListener("click", notifyMe);
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.
}
我們不再在此頁面上顯示即時示例,因為 Chrome 和 Firefox 不再允許從跨源 <iframe> 請求通知許可權,其他瀏覽器也將效仿。要檢視實際示例,請檢視我們的 待辦事項列表示例(另請參閱 即時執行的應用)。
規範
| 規範 |
|---|
| Notifications API # dom-notification-requestpermission |
瀏覽器相容性
載入中…