及時向使用者傳送實用通知。
2016 年,W3C 的 Web Applications Working Group 發布 Push API 和 Notification API,推播通知也因此標準化。這些 API 提供必要功能,讓網頁開發人員將推播通知納入網頁應用程式,使用者則可在網頁瀏覽器上接收通知並與之互動。推送訊息是網站或應用程式傳送給使用者網路瀏覽器的通知,使用者先前已授予這些網站或應用程式傳送通知的權限。這類訊息可用於提醒使用者有新內容或更新、即將到來的活動或期限,或是提供其他重要資訊。對於需要向使用者即時傳送相關資訊的應用程式 (例如新聞或體育應用程式),或是想要向使用者傳送特惠或特賣通知的電子商務網站,推播訊息特別實用。
如要註冊接收推播通知,請先檢查瀏覽器是否支援推播通知,方法是檢查 navigator 和 window 物件中是否有 serviceWorker 和 PushManager 物件。
如果支援推播通知,請使用 async 和 await 關鍵字註冊 Service Worker,並訂閱推播通知。以下範例說明如何使用 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.");
}