現已支援跨瀏覽器推播通知

向使用者傳送及時實用的通知。

推播通知在 2016 年推出的 Push API 和 Notification API 已成為 W3C「Web Applications Working Group」的一部分。這些 API 為網頁程式開發人員提供必要功能,將推播通知整合至自己的網路應用程式,以及讓使用者在網路瀏覽器上接收通知並與之互動。推播通知是指使用者之前授予傳送通知的網站或應用程式,從網站或應用程式傳送到使用者的網路瀏覽器的通知。這類訊息可用來通知使用者有新內容或最新消息,提醒他們即將到來的活動或期限,或是提供其他重要資訊。對於需要即時向使用者提供相關資訊的應用程式 (例如新聞或運動應用程式) 或電子商務網站,接收特價優惠或特價通知的電子商務網站,推送訊息特別實用。

如要註冊推播通知,請先檢查 navigatorwindow 物件中的 serviceWorkerPushManager 物件,確認瀏覽器是否支援這些功能。

如果系統支援推播通知,請使用 asyncawait 關鍵字註冊 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.");
}

瀏覽器支援

  • 42
  • 17
  • 44
  • 16

資料來源

延伸閱讀

新可互通系列的一部分