【问题标题】:Javascript Service worker onload show notificationsJavascript Service Worker onload 显示通知
【发布时间】:2016-02-12 13:49:10
【问题描述】:

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

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

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

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

【问题讨论】:

  • 您在哪里运行该代码?它是否在您已在 service worker 中注册的事件侦听器之一中?
  • @Marco 不,不是。一开始我把它放在那里,但后来我不知道如何调用这些事件来自动运行。
  • 很遗憾你做不到,我建议你看看 Service Worker Cookbook 上的例子:serviceworke.rs,它会帮助你理清思路。

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


【解决方案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  
         })  
      );  
    });

详细了解参考google的入门@9​​87654322@。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 2020-02-06
    • 2017-12-26
    相关资源
    最近更新 更多