1

我正在关注谷歌的本教程:

https://developers.google.com/web/updates/2015/03/push-notifications-on-the-open-web

我试过但不知道如何在推送通知中获取数据。

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

  var title = 'Yay a message.';  
  var body = 'We have received a push message.';  
  var icon = '/images/icon-192x192.png';  
  var tag = 'simple-push-demo-notification-tag';

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

例如,我想检索这样的数据:

self.addEventListener('push', function(event) {  
  var data = event.data;

  var title = data.title;  
  var body = data.body;  
  var icon = data.icon;  
  var tag = data.tag;

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

data是我推送到 Google Cloud Messaging 的字段之一:

$apiKey = '12345678';

$url = 'https://android.googleapis.com/gcm/send';

$post = array(
    'registration_ids' => $ids,
    'data' => $data,
    'notification' => $notification,
);

$headers = array(
    'Authorization: key=' . $apiKey,
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'GCM error: ' . curl_error($ch);
}
curl_close($ch);
4

1 回答 1

2

event.data 尚未在 chrome 中实现。尽管看起来它实际上很快就会发货。

请注意,一旦它发货,您将需要对数据服务器端进行加密,因此这将是非常重要的。然而,这对于隐藏推送消息到 GCM 服务器的内容很重要。

于 2015-12-15T09:58:47.827 回答