youbbs
youbbs
785 0 0

JS 支持跨浏览器推送

推送消息是从用户先前已授予发送通知权限的网站或应用程序发送到用户 Web 浏览器的通知。 这些消息可用于提醒用户新内容或更新。

要注册推送通知,首先通过检查导航器和窗口对象中的 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.");
}
0

See Also

Nearby


Discussion

Login Topics