Tianhe Gao

Push notifications are now supported cross-browser

https://web.dev/push-notifications-in-all-modern-browsers/

适用于向用户提供及时、相关信息的应用程序(如新闻和体育应用)或希望向用户发送特价或销售通知的电子商务网站。

检查浏览器是否支持:

1console.log(window.PushManager)
2console.log(navigator.serviceWorker)

结果:

 1// Firefox Dev v112.0b7
 2/**
 3 * function ()
 4 * ServiceWorkerContainer
 5 */
 6
 7// Chrome v111
 8/**
 9 * PushManager()
10 * ServiceWorkerContainer
11 */

如果浏览器支持,可以用 asyncawait 关键词注册 service worker 并订阅推送通知。一个 Demo:

 1// 检查浏览器是否支持推送通知
 2if ("serviceWorker" in navigator && "PushManager" in window) {
 3  try {
 4    // 注册 service worker
 5    const swReg = await navigator.serviceWorker.register("/sw.js");
 6
 7    // 订阅推送通知
 8    const pushSubscription = await swReg.pushManager.subscribe({
 9      userVisibleOnly: true
10    });
11
12    // 保存推送订阅至数据库
13    savePushSubscription(pushSubscription);
14  } catch (error) {
15    // 处理错误
16    console.error("Error subscribing for push notifications.", error)
17  }
18} else {
19  // 当前浏览器不支持推送通知
20  console.error("Push notifications are not supported by the browser.");

进一步阅读


No notes link to this note

Welcome to tell me your thoughts via "email"
UP