本程式碼研究室會逐步說明如何建構推播通知伺服器。完成程式碼研究室後,您的伺服器將具有:
- 追蹤推播通知訂閱項目 (例如用戶端選擇接收推播通知時,伺服器會建立新的資料庫記錄,並在用戶端選擇停用時刪除現有的資料庫記錄)
- 將推播通知傳送至單一用戶端
- 傳送推播通知給所有已訂閱的用戶端
本程式碼研究室的重點在於協助您從做中學習,不會深入談論概念。如要瞭解推播通知的概念,請參閱「推播通知的運作方式」一文。
本程式碼研究室的用戶端程式碼已完成。我們只會在這個程式碼研究室中實作伺服器。如要瞭解如何實作推播通知用戶端,請參閱「程式碼研究室:建構推播通知用戶端」。
如要查看完整程式碼,請參閱 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
替換為公開金鑰的值。
管理訂閱
您的用戶端會處理大部分的訂閱流程。伺服器需要儲存新的推播通知訂閱項目,並刪除舊訂閱項目。這些訂閱可讓您在日後將訊息推送至用戶端。如要進一步瞭解訂閱程序,請參閱「將用戶端訂閱推播通知」。
儲存新的訂閱資訊
- 如要預覽網站,請按下「View App」,然後按下「Fullscreen」。
- 按一下「應用程式」分頁中的「註冊 Service Worker」。狀態方塊中應會顯示類似以下內容的訊息:
Service worker registered. Scope: https://desert-cactus-sunset.glitch.me/
- 在應用程式分頁中,按一下「訂閱推送」。瀏覽器或作業系統可能會詢問您是否要讓網站傳送推播通知。按一下「Allow」(允許) (或任何瀏覽器/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>
是隨機數字。 - 請在其他瀏覽器或裝置中開啟您的應用程式,並嘗試訂閱推播通知,然後按一下「Notify all」按鈕。所有訂閱的裝置應該都會收到相同的通知 (也就是說,推播通知內文中的 ID 應相同)。
後續步驟
- 如要深入瞭解推播通知的運作方式,請參閱推播通知總覽。
- 請參閱「程式碼研究室:建構推播通知用戶端」,瞭解如何建構會要求通知權限的用戶端、訂閱裝置來接收推播通知,並使用 Service Worker 接收推播通知,並將訊息顯示為通知。