现在支持跨浏览器推送通知

推送通知在2016年随着Push API和Notification API的发布而标准化,它们是W3C的Web应用程序工作组的一部分。这些 API 为 Web 开发人员提供必要的功能,以便将推送通知合并到其 Web 应用程序中,并让用户在其 Web 浏览器上接收通知并与之交互。推送消息是从用户先前授予发送通知权限的网站或应用程序发送到用户 Web 浏览器的通知。这些消息可用于提醒用户新内容或更新,提醒他们即将发生的事件或截止日期,或提供其他重要信息。推送消息对于需要向用户提供及时相关信息的应用程序(如新闻或体育应用)特别有用,或者对于希望向用户发送有关特别优惠或销售的通知的电子商务网站。

要注册推送通知,请首先通过检查 and 对象中的 and 对象来检查您的浏览器是否支持推送通知。serviceWorkerPushManagernavigatorwindow

适用于 iOS 和 iPadOS 的 Safari 浏览器从版本 16.4 开始支持推送通知,但仅适用于已添加到主屏幕的 App。苹果称这些为主屏幕网络应用程序。

如果支持推送通知,请使用 and 关键字注册服务工作进程并订阅推送通知。下面是如何使用 JavaScript 执行此操作的示例:asyncawait

// 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.");
}

猜你喜欢

转载自blog.csdn.net/liuhao9999/article/details/130013494