GCM pushEvent问题

时间:2015-12-21 18:11:15

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

我已使用GCM api向服务工作者发送推送通知。但在我的服务工作者中没有属性数据。因此,我将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)

1 个答案:

答案 0 :(得分: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);
}

有数据定义的地方。

传递给它的数据不是来自事件(或与事件对象有关)。

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

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  
    })
  });
});