本程式碼研究室會逐步說明如何建構推播通知伺服器。完成程式碼研究室後,您就會有一個伺服器:
- 持續追蹤推播通知訂閱(例如,當用戶端選擇啟用推播通知時,伺服器會建立新的資料庫記錄,並且會在用戶端選擇退出時刪除現有的資料庫記錄)
- 傳送推播通知給單一用戶端
- 傳送推播通知給所有已訂閱的用戶端
本程式碼研究室的重點在於幫助您透過實踐方式學習,並且不會深入談論概念。如要瞭解推播通知的概念,請參閱推播通知的運作方式?一文。
本程式碼研究室的用戶端程式碼已經完成。您只需在這個程式碼研究室中實作伺服器。如要瞭解如何實作推播通知用戶端,請參閱「程式碼研究室:建構推播通知用戶端」。
請參閱 push-notifications-server-codelab-complete (來源),查看完整的程式碼。
瀏覽器相容性
本程式碼研究室已知會使用下列作業系統和瀏覽器組合:
- Windows:Chrome、Edge
- macOS:Chrome、Firefox
- Android:Chrome、Firefox
本程式碼研究室已知「無法」與下列作業系統 (或作業系統和瀏覽器組合) 搭配使用:
- macOS:Brave、Edge、Safari
- iOS
應用程式堆疊
- 伺服器是以 Express.js 為基礎建構而成。
- web-push Node.js 程式庫會處理所有推播通知邏輯。
- 使用 lowdb 將訂閱資料寫入 JSON 檔案。
您不必使用上述任何技術即可實作推播通知。 我們之所以選擇這些技術,是因為它們提供可靠的程式碼研究室體驗。
設定
取得可編輯的程式碼副本
這些操作說明右側的程式碼編輯器在本程式碼研究室中將稱為「Glitch UI」。
- 按一下「Remix to Edit」,讓專案可供編輯。
設定驗證方法
您需要使用驗證金鑰設定伺服器和用戶端,才能讓推播通知正常運作。如要瞭解原因,請參閱「簽署網路推送通訊協定要求」。
- 依序點選「Tools」和「Terminal」來開啟 Glitch 終端機。
- 在終端機中執行
npx web-push generate-vapid-keys
。請複製私密金鑰和公開金鑰值。 - 開啟
.env
並更新VAPID_PUBLIC_KEY
和VAPID_PRIVATE_KEY
。將VAPID_SUBJECT
設為mailto:test@test.test
。所有這些值都應該以雙引號括住。更新完成後,.env
檔案應如下所示:
VAPID_PUBLIC_KEY="BKiwTvD9HA…"
VAPID_PRIVATE_KEY="4mXG9jBUaU…"
VAPID_SUBJECT="mailto:test@test.test"
- 關閉 Glitch 終端機。
- 開啟
public/index.js
。 - 將
VAPID_PUBLIC_KEY_VALUE_HERE
替換成公開金鑰的值。
管理訂閱
您的用戶端會處理大部分的訂閱程序。伺服器需要執行的主要工作是儲存新的推播通知訂閱項目,以及刪除舊訂閱項目。這些訂閱可讓您在日後將訊息推送至用戶端。如要進一步瞭解訂閱程序,請參閱「訂閱用戶端以推送通知」。
儲存新的訂閱資訊
- 如要預覽網站,請按下「查看應用程式」,然後按下「全螢幕」圖示 。
- 在應用程式分頁中,按一下「Register Service Worker」。狀態方塊中會顯示類似以下的訊息:
Service worker registered. Scope: https://desert-cactus-sunset.glitch.me/
- 在應用程式分頁中,按一下「訂閱推送」。瀏覽器或作業系統可能會詢問您是否要讓網站傳送推播通知。按一下 [允許] (或瀏覽器/OS 使用的對等詞組)。狀態方塊中會顯示類似以下的訊息:
Service worker subscribed to push. Endpoint: https://fcm.googleapis.com/fcm/send/…
- 按一下 Glitch UI 中的「View Source」,返回程式碼。
- 依序點選「Tools」和「Logs」來開啟 Glitch 記錄檔。您應該會看到
/add-subscription
,後面接著一些資料。/add-subscription
是用戶端在想要訂閱推播通知時,傳送 POST 要求的網址。以下資料是您要儲存的用戶端訂閱資訊。 - 開啟
server.js
。 - 使用下列程式碼更新
/add-subscription
路徑處理常式邏輯:
app.post('/add-subscription', (request, response) => {
console.log('/add-subscription');
console.log(request.body);
console.log(`Subscribing ${request.body.endpoint}`);
db.get('subscriptions')
.push(request.body)
.write();
response.sendStatus(200);
});
刪除舊的訂閱資訊
- 返回應用程式分頁。
- 按一下「取消訂閱推送通知」。
- 再次查看毛刺記錄。您應該會看到
/remove-subscription
,後面接著用戶端的訂閱資訊。 - 使用下列程式碼更新
/remove-subscription
路徑處理常式邏輯:
app.post('/remove-subscription', (request, response) => {
console.log('/remove-subscription');
console.log(request.body);
console.log(`Unsubscribing ${request.body.endpoint}`);
db.get('subscriptions')
.remove({endpoint: request.body.endpoint})
.write();
response.sendStatus(200);
});
傳送通知
如「傳送推送訊息」一節所述,伺服器實際上並未將推送訊息直接傳送至用戶端。而是透過推送服務完成。基本上,您的伺服器會啟動網路服務要求 (網路推送通訊協定要求) 至使用者瀏覽器廠商所擁有的網路服務 (推送服務),藉此啟動推送訊息給用戶端的程序。
- 使用下列程式碼更新
/notify-me
路徑處理常式邏輯:
app.post('/notify-me', (request, response) => {
console.log('/notify-me');
console.log(request.body);
console.log(`Notifying ${request.body.endpoint}`);
const subscription =
db.get('subscriptions').find({endpoint: request.body.endpoint}).value();
sendNotifications([subscription]);
response.sendStatus(200);
});
- 使用下列程式碼更新
sendNotifications()
函式:
function sendNotifications(subscriptions) {
// TODO
// Create the notification content.
const notification = JSON.stringify({
title: "Hello, Notifications!",
options: {
body: `ID: ${Math.floor(Math.random() * 100)}`
}
});
// Customize how the push service should attempt to deliver the push message.
// And provide authentication information.
const options = {
TTL: 10000,
vapidDetails: vapidDetails
};
// Send a push message to each client specified in the subscriptions array.
subscriptions.forEach(subscription => {
const endpoint = subscription.endpoint;
const id = endpoint.substr((endpoint.length - 8), endpoint.length);
webpush.sendNotification(subscription, notification, options)
.then(result => {
console.log(`Endpoint ID: ${id}`);
console.log(`Result: ${result.statusCode}`);
})
.catch(error => {
console.log(`Endpoint ID: ${id}`);
console.log(`Error: ${error} `);
});
});
}
- 使用下列程式碼更新
/notify-all
路徑處理常式邏輯:
app.post('/notify-all', (request, response) => {
console.log('/notify-all');
response.sendStatus(200);
console.log('Notifying all subscribers');
const subscriptions =
db.get('subscriptions').cloneDeep().value();
if (subscriptions.length > 0) {
sendNotifications(subscriptions);
response.sendStatus(200);
} else {
response.sendStatus(409);
}
});
- 返回應用程式分頁。
- 按一下「取消訂閱推送內容」,然後再次點選「訂閱推送」。 這是因為如前所述,每當您編輯程式碼,且專案設為在啟動時刪除資料庫,Glitch 都會重新啟動專案。
- 按一下「通知我」。您應該會收到推播通知。標題應為
Hello, Notifications!
,內文應為ID: <ID>
,其中<ID>
是隨機數字。 - 在其他瀏覽器或裝置中開啟應用程式,並嘗試訂閱推播通知,然後按一下「全部通知」按鈕。您訂閱的所有裝置應該都會收到相同的通知 (即推播通知內文中的 ID 應相同)。
後續步驟
- 如要深入瞭解推播通知的運作方式,請參閱推播通知總覽。
- 請參閱程式碼研究室:建構推播通知用戶端,瞭解如何建構要求通知權限的用戶端、訂閱裝置以接收推播通知,以及使用服務工作站接收推播通知,以及將訊息顯示為通知。