未捕获(承诺):TypeError:无法读取未定义的属性“ showNotification”

时间:2019-05-29 14:52:45

标签: angular google-chrome push-notification

我想向我的应用程序添加浏览器通知,所以我创建了此功能:

showNotification() {
    navigator.serviceWorker.getRegistration()
    .then( function(reg){

      reg.showNotification('finish button clicked');
    });
  }
我从这里打来的

stop() {
this.showNotification();
}

但我收到此错误:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'showNotification' of undefined

我在做什么错?是否有更好的方法来利用浏览器通知,而不会收到来自后端的任何消息?

2 个答案:

答案 0 :(得分:0)

您的serviceWorkerRegistration流程可能有问题,

您还必须注意,getRegistration()返回的承诺可以解决serviceWorkerRegistration objectundefined,因此请在致电节目通知之前进行检查

showNotification() {
    navigator.serviceWorker.getRegistration()
    .then( function(reg){
        if(reg) {
        reg.showNotification('finish button clicked');
       } else {
         console.log('GOT undefined');
       }
    });
  }

请参见serviceWorkerRegistration in Angular

要查看服务人员的当前状态,您可能会提出以下建议:

navigator.serviceWorker.register('/sw.js', {scope: '/'})
  .then(function (registration) {
    var serviceWorker;
    if (registration.installing) {
      serviceWorker = registration.installing;
    } else if (registration.waiting) {
      serviceWorker = registration.waiting;
    } else if (registration.active) {
      serviceWorker = registration.active;
    }

    if (serviceWorker) {
      console.log("ServiceWorker phase:", serviceWorker.state);

      serviceWorker.addEventListener('statechange', function (e) {
        console.log("ServiceWorker phase:", e.target.state);
      });
    }
  }).catch(function (err) {
    console.log('ServiceWorker registration failed: ', err);
  });

答案 1 :(得分:0)

要获得注册服务人员,您必须在getRegistraion中传递作用域URL

例如:

 if ('serviceWorker' in navigator) {
   
           navigator.serviceWorker.getRegistration('./firebase-cloud-messaging-push-scope').then(function(registration)  {                         
                    setTimeout(() => {
                        registration.showNotification(notificationTitle,  notificationOptions);
                        registration.update();
                    }, 100);
                }).catch(function (err) {
                    console.log("No Service Worker Registered", err);
                })

 }