【问题标题】:GCM pushEvent issueGCM pushEvent 问题
【发布时间】:2016-03-27 21:25:24
【问题描述】:

我已经使用 GCM api 向 service-worker 发送了推送通知。但是在我的 service-worker 中没有属性数据。因此,我将 event.data 设为未定义。

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

var data = event.data;
var title = data.title;
var body = data.body;
var icon = '/images/image.png';  
var tag = 'simple-push-demo-notification-tag';

event.waitUntil(function() {
    self.registration.showNotification(title, {  
        body: body,  
        icon: icon,  
        tag: tag  
     })
   });
 }); 

在下面的代码中,我调用了 GCM api。

uri = 'https://android.googleapis.com/gcm/send'
payload = json.dumps({
             'registration_ids': [
                User.objects.filter(id=user_id)[0].push_key     
                 ], 
              'data': json.dumps({'title':'New notification','message': 'new message'}) 
           })
headers = {
           'Content-Type': 'application/json',
           'Authorization': 'key=<Project key>'
         } 
 requests.post(uri, data=payload, headers=headers)

【问题讨论】:

    标签: push-notification google-cloud-messaging service-worker web-push push-api


    【解决方案1】:

    这看起来您已经获取了部分代码,而不是全部,因此它无法正常工作。

    如果你在简单的push demo repo,有一个函数showNotification。

    Here for Ref

    function showNotification(title, body, icon, data) {
      console.log('showNotification');
      var notificationOptions = {
        body: body,
        icon: icon ? icon : '/images/touch/chrome-touch-icon-192x192.png',
        tag: 'simple-push-demo-notification',
        data: data
      };
      return self.registration.showNotification(title, notificationOptions);
    }
    

    数据是在哪里定义的。

    传入 this 的数据不是来自事件(或与事件对象有任何关系)。

    要让您的代码运行,只需简化它:

    self.addEventListener('push', function(event) {  
      console.log('Received a push message', event);
      console.log('testing');
    
      var title = 'My Title';
      var body = 'My notification body';
      var icon = '/images/image.png';  
      var tag = 'simple-push-demo-notification-tag';
    
      event.waitUntil(function() {
        self.registration.showNotification(title, {  
          body: body,  
          icon: icon,  
          tag: tag  
        })
      });
    }); 
    

    【讨论】:

    • 感谢马特的澄清。顺便说一句,我从您在博客中的文章中了解到数据存储在事件中。 [链接] (gauntface.com/blog/2014/12/15/push-notifications-service-worker)。据我了解,GCM api 触发 service-worker,然后发送推送通知。在您提到的链接(天气数据示例)中,如何为 api 提供参数(例如城市名称)?会通过 GCM api 提供吗?如果是,那么我如何在服务工作者中获取该参数(尽管 event.data?)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    相关资源
    最近更新 更多