Notification
注意:此功能在 Web Workers 中可用。
Notification 介面是 Notifications API 的一部分,用於配置和向用戶顯示桌面通知。
這些通知的外觀和特定功能因平臺而異,但它們通常提供一種異步向使用者提供資訊的方式。
建構函式
Notification()-
建立
Notification物件的新例項。
靜態屬性
還繼承了其父介面 EventTarget 的屬性.
Notification.permission只讀-
一個字串,表示顯示通知的當前許可權。可能的值為:
denied— 使用者拒絕顯示通知。granted— 使用者同意顯示通知。default— 使用者選擇未知,因此瀏覽器將如同該值為 denied 一樣處理。
Notification.maxActions只讀 實驗性-
裝置和使用者代理支援的最大運算元。
例項屬性
還繼承了其父介面 EventTarget 的屬性.
Notification.actions只讀 實驗性-
在建構函式的
options引數中指定的通知的運算元組。 Notification.badge只讀-
一個字串,包含當沒有足夠空間顯示通知本身時(例如,Android 通知欄)用於表示通知的影像的 URL。在 Android 裝置上,徽章應相容高達 4x 解析度的裝置,大約 96 x 96 畫素,並且影像會自動被遮罩。
Notification.body只讀-
在建構函式的
options引數中指定的通知的主體字串。 Notification.data只讀-
返回通知資料的結構化克隆。
Notification.dir只讀-
在建構函式的
options引數中指定的通知的文字方向。 Notification.icon只讀-
在建構函式的
options引數中指定的用作通知圖示的影像的 URL。 Notification.image只讀 實驗性-
在建構函式的
options引數中指定的將作為通知一部分顯示的影像的 URL。 Notification.lang只讀-
在建構函式的
options引數中指定的通知的語言程式碼。 Notification.renotify只讀 實驗性-
指定使用者在新通知替換舊通知後是否應收到通知。
Notification.requireInteraction只讀-
一個布林值,指示通知應保持活動狀態,直到使用者單擊或關閉它,而不是自動關閉。
Notification.silent只讀-
指定通知是否應靜音 - 即,無論裝置設定如何,都不應發出聲音或振動。
Notification.tag只讀-
在建構函式的
options引數中指定的通知的 ID(如果有)。 Notification.timestamp只讀 實驗性-
指定建立通知或適用通知的時間(過去、現在或將來)。
Notification.title只讀-
在建構函式的第一個引數中指定的通知的標題。
Notification.vibrate只讀 實驗性-
指定具有振動硬體的裝置的振動模式。
靜態方法
還繼承了其父介面 EventTarget 的方法.
Notification.requestPermission()-
請求使用者顯示通知的許可權。
例項方法
還繼承了其父介面 EventTarget 的方法.
Notification.close()-
以程式設計方式關閉通知例項。
事件
還繼承了其父介面 EventTarget 的事件.
示例
假設此基本 HTML
<button>Notify me!</button>
可以透過以下方式傳送通知 - 這裡我們提供了一套相當冗長且完整的程式碼,如果您想先檢查是否支援通知,然後檢查當前源是否已被授予傳送通知的許可權,如果需要則請求許可權,然後再發送通知,就可以使用這些程式碼。
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> 請求通知許可權,其他瀏覽器也將效仿。要檢視示例的實際效果,請檢視我們的 待辦事項列表示例(也請參閱 應用即時執行)。
注意: 在上面的示例中,我們在使用者手勢(單擊按鈕)的響應中生成通知。這不僅是最佳實踐 - 您不應該向使用者傳送他們未同意的通知 - 而且將來瀏覽器將明確禁止未響應使用者手勢觸發的通知。例如,Firefox 從 72 版本開始就已經這樣做了。
規範
| 規範 |
|---|
| Notifications API # api |
瀏覽器相容性
載入中…