在本程式碼研究室中,您將使用 Notifications API 的基本功能執行下列操作:
- 要求傳送通知的權限
- 傳送通知
- 試用通知選項
熟悉範例應用程式及其程式碼
首先,請在新 Chrome 分頁中查看即時應用程式:
按下 `Control+Shift+J` 鍵 (在 Mac 上為 `Command+Option+J` 鍵) 開啟開發人員工具。 再按一下「Console」(控制台) 分頁標籤即可。
控制台應會顯示以下訊息:
Notification permission is default
如果您不知道這是什麼意思,別擔心,很快就會揭曉!
在即時應用程式中,按一下「Request permission to send notifications」和「Send a notification」按鈕。
控制台會從幾個函式存根 (
requestPermission
和sendNotification
) 列印「TODO」訊息。您將在本程式碼研究室中實作這些函式。
現在來看看範例應用程式的程式碼。
開啟 public/index.js
,並查看現有程式碼的幾個重要部分:
showPermission
函式會使用 Notifications API 取得網站目前的權限狀態,並記錄到控制台中:// Print current permission state to console; // update onscreen message. function showPermission() { let permission = Notification.permission; console.log('Notification permission is ' + permission); let p = document.getElementById('permission'); p.textContent = 'Notification permission is ' + permission; }
要求權限前,權限狀態為
default
。 在default
權限狀態下,網站必須先要求並取得權限,才能傳送通知。requestPermission
函式是虛設常式:// Use the Notification API to request permission to send notifications. function requestPermission() { console.log('TODO: Implement requestPermission()'); }
您將在下一個步驟中實作此函式。
sendNotification
函式是虛設常式:// Use the Notification constructor to create and send a new Notification. function sendNotification() { console.log('TODO: Implement sendNotification()'); }
實作
requestPermission
後,您將實作此函式。window.onload
事件監聽器會在網頁載入時呼叫showPermission
函式,在控制台和網頁上顯示目前的權限狀態:window.onload = () => { showPermission(); };
要求傳送通知的權限
在這個步驟中,您會新增要求使用者授權傳送通知的功能。
您可以使用 Notification.requestPermission()
方法觸發彈出式視窗,要求使用者允許或封鎖來自您網站的通知。
將 public/index.js 中的
requestPermission
函式存根替換為下列程式碼:// Use the Notification API to request permission to send notifications. function requestPermission() { Notification.requestPermission() .then((permission) => { console.log('Promise resolved: ' + permission); showPermission(); }) .catch((error) => { console.log('Promise was rejected'); console.log(error); }); }
重新載入顯示即時應用程式的 Chrome 分頁。
在應用程式的即時介面中,按一下「Request permission to send notifications」(要求傳送通知的權限)。畫面上會顯示彈出式視窗。
使用者可以對權限彈出式視窗做出下列三種回應:
使用者回覆 | 通知權限狀態 |
---|---|
使用者選取「允許」 | granted |
使用者選取「封鎖」 | denied |
使用者關閉彈出式視窗,但未做出選擇 | default |
如果使用者按一下「允許」:
Notification.permission
設為granted
。網站就能顯示通知。
後續對
Notification.requestPermission
的呼叫會解析為granted
,不會顯示彈出式視窗。
如果使用者點選「封鎖」:
Notification.permission
設為denied
。網站無法向使用者顯示通知。
後續對
Notification.requestPermission
的呼叫會解析為denied
,不會顯示彈出式視窗。
如果使用者關閉彈出式視窗:
Notification.permission
仍為default
。網站將無法向使用者顯示通知。
後續呼叫
Notification.requestPermission
會產生更多彈出式視窗。不過,如果使用者持續關閉彈出式視窗,瀏覽器可能會封鎖網站,將
Notification.permission
設為denied
。系統隨後便無法向使用者顯示權限要求彈出式視窗或通知。撰寫本文時,瀏覽器在使用者關閉通知權限彈出式視窗後採取的行為仍可能有所變更。處理這類情況的最佳方式,就是一律在使用者發起的互動後要求通知權限,讓他們有所準備並瞭解情況。
傳送通知
在這個步驟中,您將傳送通知給使用者。
您將使用 Notification
建構函式建立新通知,並嘗試顯示該通知。
如果權限狀態為 granted
,系統就會顯示通知。
將 index.js 中的
sendNotification
函式存根替換為下列程式碼:// Use the Notification constructor to create and send a new Notification. function sendNotification() { let title = 'Test'; let options = { body: 'Test body', // Other options can go here }; console.log('Creating new notification'); let notification = new Notification(title, options); }
Notification
建構函式會採用兩個參數:title
和options
。options
是物件,其屬性代表視覺設定和可納入通知的資料。詳情請參閱 MDN 說明文件中的通知參數。重新整理顯示即時應用程式的 Chrome 分頁,然後按一下「傳送通知」按鈕。畫面上應會顯示「
Test body
」文字的通知。
未經許可傳送通知會發生什麼情況?
在這個步驟中,您將新增幾行程式碼,以便查看在未取得使用者授權的情況下嘗試顯示通知時,會發生什麼情況。
- 在
public/index.js
中,於sendNotification
函式結尾定義新通知的onerror
事件處理常式:
// Use the Notification constructor to create and send a new Notification.
function sendNotification() {
let title = 'Test';
let options = {
body: 'Test body',
// Other options can go here
};
console.log('Creating new notification');
let notification = new Notification(title, options);
notification.onerror = (event) => {
console.log('Could not send notification');
console.log(event);
};
}
如要觀察通知權限錯誤,請按照下列步驟操作:
按一下 Chrome 網址列旁邊的鎖頭圖示,然後將網站的通知權限設定重設為預設值。
按一下「要求傳送通知的權限」,然後在彈出式視窗中選取「封鎖」。
按一下「傳送通知」,看看會發生什麼事。 錯誤文字 (
Could not send notification
) 和事件物件會記錄到控制台。
視需要再次重設網站的通知權限。 您可以嘗試多次要求權限並關閉彈出式視窗,看看會發生什麼情況。
試用通知選項
您現在已瞭解如何要求權限及傳送通知的基本概念。您也瞭解使用者回覆對應用程式顯示通知的影響。
現在建立通知時,您可以試用多種視覺和資料選項。 下方列出所有可用的選項。 (如要進一步瞭解這些選項,請參閱 MDN 上的通知說明文件)。
請注意,瀏覽器和裝置會以不同方式實作這些選項,因此建議在不同平台上測試通知,瞭解通知的顯示方式。
let options = {
dir: 'auto', // Text direction
lang: 'en-US', // A language tag
badge: '/orange-cat.png', // Display when insufficient room
body: 'Hello World', // Body text
tag: 'mytag', // Tag for categorization
icon: '/line-cat.png', // To display in the notification
image: '/orange-cat.png', // To display in the notification
data: { // Arbitrary data; any data type
cheese: 'I like cheese',
pizza: 'Excellent cheese delivery mechanism',
arbitrary: {
faveNumber: 42,
myBool: true
}},
vibrate: [200, 100, 200], // Vibration pattern for hardware
renotify: false, // Notify if replaced? Default false
requireInteraction: false,// Active until click? Default false
/*
actions: // Array of NotificationActions
// Only usable with a service worker
[{
action: 'shop',
title: 'Shop!',
icon: '/bags.png'
},],
*/
}
如需更多想法,請參閱 Peter Beverloo 的通知產生器!
請參閱本系列下一個程式碼研究室「使用 Service Worker 處理通知」,進一步瞭解相關資訊!