2

我已经使用 GCM api 向服务人员发送了推送通知。但是在我的 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)
4

1 回答 1

1

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

如果你在简单的推送演示 repo 中,有一个函数 showNotification。

这里参考

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  
    })
  });
}); 
于 2015-12-21T19:37:38.917 回答