Javascript服务工作者onload显示通知

时间:2016-02-12 13:49:11

标签: javascript google-chrome notifications push-notification service-worker

我有一个已注册的服务工作者,但我想循环一个函数来检查服务器上的更新,并在关闭选项卡时显示通知。

使用serviceworker.js中的以下代码,我收到错误; "未捕获(在承诺中)TypeError:ServiceWorkerRegistration上没有可用的活动注册。"

self.registration.showNotification(title, {
        body: 'We have received a push message',
        icon: '',
        tag: ''
})

我希望在浏览器打开时弹出通知,就像Facebook一样。

1 个答案:

答案 0 :(得分:1)

嗯,你需要首先了解service-worker

的生命周期
    // listen for a push notification from gcm, as only it can reiterate 
    // your push-notifications to your clients subscriber id
    // put your code inside listener

       self.addEventListener('push', function(event) {  
          console.log('Received a push message', event);

         // here you can make rest calls to fetch data against the subscriber-id 
         // and accordingly, set data 
         // keep in mind that your server sends push notifications to gcm
         // and then your subscribers receive them here

         var title = 'title' || 'data-from-rest-call';  
         var body = 'body' || 'data-from-rest-call';  
         var icon = '/your image path' || 'data-from-rest-call';  
         var tag = 'tag' || 'data-from-rest-call';

         // waitUntil is a callback, it triggers when the push is ready.
         event.waitUntil(  
         //here your ready notifications get triggered
         self.registration.showNotification(title, {  
           body: body,  
           icon: icon,  
           tag: tag  
         })  
      );  
    });
  

请参阅谷歌的web-push-notifications入门,了解详细信息。