微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

通过 React js (pwa) 中的 Service Worker 推送通知

如何解决通过 React js (pwa) 中的 Service Worker 推送通知

我正在 PWA 中尝试使用 Service Worker 推送通知注册 Service Worker 后。我为安装和激活添加了事件侦听器,并在激活事件侦听器内部添加了通过推送管理器订阅注册推送服务的逻辑,但问题是控制台中没有关于激活和安装事件的日志,而试图通过 chrome dev 测试推送工具而不是在这里工作是我的代码

index.js

serviceWorker.register()

worker.js

const publicvapidKey = "BOdud_KdO16dL40D56LbksLa6ElXFAJu-2XEdIKQUmehzomo6FES2jJ1niaUYrCobfI8U5rkqeQNjPB03mKZMvY"

export const register = () => {
  console.log('register called');
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/worker.js')
      .then((responseRegister) => {
        console.log('register object',responseRegister);
        window.registration = responseRegister;
      })
      .catch((err) => {
        console.log('error is ',err);
      })
  }
}

export const unregister = () => {
  console.log("unregister called");
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.getRegistrations()
      .then(function (registrations) {
        console.log('registrations',registrations);
        for (let registration of registrations) {
          registration.unregister()
        }
      }).catch(function (err) {
        console.log('Service Worker registration Failed: ',err);
      });
  }
}

window.self.addEventListener('install',(event) => {
  console.log('service worker installed',event);
})

window.self.addEventListener('activate',(event) => {
  console.log('service worker activated',event);

  console.log('window',window);
  window.registration.pushManager.subscribe({
    userVisibleOnly: true,applicationServerKey: urlBase64ToUint8Array(publicvapidKey)
  }).then((subscription) => {
    console.log('subscription',subscription);
  })
    .catch((err) => {
      console.log('error in subscribing to push',err);
    });
})

window.self.addEventListener("push",e => {
  const data = e.data.json();
  console.log("Push Recieved...");
  window.registration.showNotification(
    data.title,{
    body: "Notified by Traversy Media!",});
});

function urlBase64ToUint8Array(base64String) {
  const padding = "=".repeat((4 - base64String.length % 4) % 4);
  const base64 = (base64String + padding)
    .replace(/\-/g,"+")
    .replace(/_/g,"/");

  const rawData = window.atob(base64);
  const outputArray = new Uint8Array(rawData.length);

  for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i);
  }
  return outputArray;
}

enter image description here

点击推送不会触发任何推送事件

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。