现在可以跨浏览器使用推送通知

向用户及时提供有用的通知。

2016 年,随着 Push API 和 Notification API(属于 W3C 的 Web 应用工作组)的发布,推送通知已实现标准化。这些 API 为网络开发者提供了必要的功能,以便他们将推送通知整合到他们的 Web 应用中,以及用户可以在其网络浏览器上接收通知并与之互动。推送消息是从网站或应用向用户网络浏览器发送的通知,且用户之前已授予发送通知的权限。这些消息可用于提醒用户有新内容或更新,提醒他们即将到来的活动或截止日期,或者提供其他重要信息。推送消息特别适用于需要及时向用户提供相关信息的应用(例如新闻或体育应用),或者希望向用户发送特别优惠或促销通知的电子商务网站。

如需注册推送通知,请先检查 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

来源

补充阅读材料

全新可互操作系列课程的一部分