在 Chrome 推送通知中的 Service Worker 中的 GCM 注册 ID

10
我可以发送推送通知,在服务工作器中进行服务调用,我只想在该服务调用中发送GCM注册ID。如何在服务工作器中获取注册ID或订阅ID?
这是我的代码:
self.addEventListener('push', function(event) {
  console.log('Received a push message from local', event);

  var title = 'My title file. Testing on';
  var body = 'New Push Message.';
  var icon = 'refresh_blueicon.png';
  var tag = 'my-push-tag';

  event.waitUntil(
// Here i need to wind GCM Registration id / Subscription id with external service call


  fetch('http://localhost/pushMsg/Push_Notification/msg.php').then(function(response){

     if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' +
        response.status);
        throw new Error();
      }
       // Examine the text in the response
      return response.json().then(function(data) {

       self.registration.showNotification(data.title, {
          body: data.msg,
          icon: icon,
          tag: tag
        })
  })
  })


  );
});


self.addEventListener('notificationclick', function(event) {
  console.log('On notification click: ', event.notification.tag);
  // Android doesn’t close the notification when you click on it
  // See: http://crbug.com/463146
  event.notification.close();

  // This looks to see if the current is already open and
  // focuses if it is
  event.waitUntil(clients.matchAll({
    type: "window"
  }).then(function(clientList) {
    for (var i = 0; i < clientList.length; i++) {
      var client = clientList[i];
      if (client.url == '/' && 'focus' in client)
        return client.focus();
    }
    if (clients.openWindow)
      return clients.openWindow('/');
  }));

});

http://localhost/pushMsg/Push_Notification/msg.php的目的是什么? - Sanjay Radadiya
@sanjayradadiya,这是获取JSON数据以在通知中显示标题、图像、简短描述等内容。 - Yogendra
1个回答

10

如果您已经为用户订阅了推送服务,那么您应该已经可以在pushManager对象上使用订阅服务。因此,以下代码应该有效:

registration.pushManager.getSubscription().then(function(subscription) {
  console.log("got subscription id: ", subscription.endpoint)
});

那就是整个终端点了,所以如果你只想获取id,你可以这样做:

subscription.endpoint.split("/").slice(-1))

具体来说,在Chrome 44+中,subscription.endpoint是您想要的内容,在其他浏览器添加支持时也是如此。如果您仍然关心Chrome 43,请阅读http://updates.html5rocks.com/2015/03/push-notificatons-on-the-open-web#supporting-pre-chrome-44-push。 - Jeff Posnick
registration.pushManager.getSubscription().then(function(subscription) { console.log("got subscription id: ", subscription.endpoint) });在我的情况下,上述代码的输出如下: https://android.googleapis.com/gcm/send - Yogendra
那么你不知道如何获取订阅 ID 却已经获得了订阅?我不知道这是怎么可能的。也许与 API 配置有关? - Brendan Ritchie
实际上,如果您使用的是较旧版本的Chrome,请检查订阅对象中是否有其他内容,例如subscription.subscriptionId。 - Brendan Ritchie
1
我该如何在我的服务工作者中获取订阅端点(subscription endpoint)? - rat
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接