簡介
Notifications API 可讓您以被動 (新電子郵件、推文或日曆活動) 和使用者互動的通知 (不論焦點位於哪一個分頁),向使用者顯示特定事件的通知。有草稿規格,但這目前並非任何標準。
只要按照下列簡單的步驟操作,幾分鐘內就能實作通知:
步驟 1:檢查 Notifications API 支援情形
系統會檢查是否支援 webkitNotifications
。請注意,webkitNotifications
的名稱是草稿規格的一部分,因此最終規格將改為使用 notifications() 函式。
// check for notifications support
// you can omit the 'window' keyword
if (window.webkitNotifications) {
console.log("Notifications are supported!");
}
else {
console.log("Notifications are not supported for this Browser/OS version yet.");
}
步驟 2:允許使用者將權限授予網站以顯示通知
如果使用者未手動授予網站顯示通知的權限,任何我們提及的建構函式都會擲回安全性錯誤。如要處理例外狀況,您可以使用 try-catch 陳述式,也可以使用 checkPermission
方法達成相同目的。
document.querySelector('#show_button').addEventListener('click', function() {
if (window.webkitNotifications.checkPermission() == 0) { // 0 is PERMISSION_ALLOWED
// function defined in step 2
window.webkitNotifications.createNotification(
'icon.png', 'Notification Title', 'Notification content...');
} else {
window.webkitNotifications.requestPermission();
}
}, false);
如果網頁應用程式沒有顯示通知的權限,requestPermission
方法會顯示資訊列:
不過,請「務必」記住,requestPermission
方法只適用於使用者動作 (例如滑鼠或鍵盤事件) 觸發的事件處理常式,以免非預期的資訊列。在此情況下,使用者動作是 ID 為「show_button」的按鈕點擊次數。如果使用者尚未明確點擊觸發 requestPermission
的按鈕或連結,上述程式碼片段無法運作。
步驟 3:附加事件監聽器和其他動作
document.querySelector('#show_button').addEventListener('click', function() {
if (window.webkitNotifications.checkPermission() == 0) { // 0 is PERMISSION_ALLOWED
// function defined in step 2
notification_test = window.webkitNotifications.createNotification(
'icon.png', 'Notification Title', 'Notification content...');
notification_test.ondisplay = function() { ... do something ... };
notification_test.onclose = function() { ... do something else ... };
notification_test.show();
} else {
window.webkitNotifications.requestPermission();
}
}, false);
在這個階段,您可能會想封裝所有這些事件和動作來建立自己的通知類別,確保程式碼更加簡潔,但這並不在本教學課程的討論範圍內。