在本程式碼研究室中,您將使用 Notifications API 的基本功能:
- 要求傳送通知的權限
- 傳送通知
- 嘗試各種通知選項
重混範例應用程式,在新分頁中查看
系統會自動封鎖嵌入式 Glitch 應用程式的通知,因此您無法在本頁面預覽應用程式。請依照下列步驟操作:
- 按一下「Remix to Edit」讓專案可供編輯。
- 如要預覽網站,請按下「View App」,然後按下「Fullscreen」
。
Glitch 應該會在新的 Chrome 分頁中開啟:
在完成本程式碼研究室的過程中,請變更本頁面內嵌 Glitch 中的程式碼。使用現有的應用程式重新整理新分頁,即可查看變更內容。
熟悉啟動應用程式及其程式碼
請先在新的 Chrome 分頁中查看上線的應用程式:
按下「Control + Shift + J」鍵 (或在 Mac 上按下「Command + Option + J」鍵) 即可開啟開發人員工具。 再按一下「Console」(控制台) 分頁標籤即可。
您應該會在控制台中看到以下訊息:
Notification permission is default
如果您不清楚這代表什麼意思,別擔心,很快就會看到全部資料!
按一下執行中應用程式中的按鈕:「要求傳送通知的權限」和「傳送通知」。
控制台會輸出幾個函式虛設常式的「TODO」訊息:
requestPermission
和sendNotification
。以下是您將在本程式碼研究室中實作的函式。
現在,我們來看看本頁面內嵌 Glitch 中範例應用程式的程式碼。開啟 public/index.js
,並查看現有程式碼的幾個重要部分:
showPermission
函式會使用通知 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 分頁。
在實際的應用程式介面中,按一下「要求傳送通知的權限」。畫面上會隨即顯示彈出式視窗,
使用者可以針對權限彈出式視窗做出三個回應。
使用者回應 | 通知權限狀態 |
---|---|
使用者選取「允許」 | 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 分頁,然後按一下「Send notifications」按鈕。這時應該會顯示一則含有「
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 的通知產生器!
如果遇到困難,請參考本程式碼研究室的完整程式碼:glitch.com/edit/#!/codelab-notifications-get-started-completed
請參閱本系列的下一個程式碼研究室:使用 Service Worker 處理通知,進一步瞭解詳情!