向使用者提供及時且實用的通知。
推播通知在 2016 年標準化,並發布推播 API 和通知 API,這兩者都是 W3C 的網路應用程式工作小組的一部分。這些 API 提供必要功能,可讓網頁開發人員將推播通知整合至網頁應用程式,並讓使用者在網頁瀏覽器中接收及互動通知。推送訊息是指從使用者先前授權傳送通知的網站或應用程式,傳送至使用者網頁瀏覽器的通知。這類訊息可用於提醒使用者有新內容或更新、提醒他們即將到期的活動或截止日期,或提供其他重要資訊。推播訊息特別適合需要向使用者提供即時相關資訊的應用程式,例如新聞或運動應用程式,或是想傳送特價或特賣資訊的電子商務網站。
如要訂閱推播通知,請先檢查瀏覽器是否支援推播通知,方法是在 navigator
和 window
物件中查看 serviceWorker
和 PushManager
物件。
如果支援推播通知,請使用 async
和 await
關鍵字註冊服務工作者,並訂閱推播通知。以下範例說明如何使用 JavaScript 執行這項操作:
// Check if the browser supports push notifications.
if ("serviceWorker" in navigator && "PushManager" in window) {
try {
// Register the service worker.
const swReg = await navigator.serviceWorker.register("/sw.js");
// Subscribe for push notifications.
const pushSubscription = await swReg.pushManager.subscribe({
userVisibleOnly: true
});
// Save the push subscription to the database.
savePushSubscription(pushSubscription);
} catch (error) {
// Handle errors.
console.error("Error subscribing for push notifications.", error);
}
} else {
// Push notifications are not supported by the browser.
console.error("Push notifications are not supported by the browser.");
}