2

我的 service-worker.js 收到来自 GCM 的通知时出现错误

self.addEventListener('push', function(event) {
  console.log('Received a push message', event);
  registration.pushManager.getSubscription().then(function(subscription) {
    console.log("got subscription id: ", subscription.endpoint)
    var endpointSplit = subscription.endpoint.split('/');
    var endpoint = endpointSplit[endpointSplit.length-1];
    return fetch('/api/notifications/'+endpoint).then(function(res){
      return res.json().then(function(payload){
        return event.waitUntil(
          self.registration.showNotification(payload.title, {
            body: payload.body,
            icon: payload.icon,
            tag: payload.tag,
            data: payload
          })
        );
      }).catch(function(err){
        console.log("Error in notifications ",err)
      })
    })
  });
});

使用上面的代码,我可以完成 gcm chrome web 通知的实现,但是我在控制台中遇到了错误。

Uncaught (in promise) DOMException: Failed to execute 'waitUntil' on 'ExtendableEvent': The event handler is already finished.
    at Error (native)
    at http://localhost:9000/service-worker.js:9:18
4

1 回答 1

4

您需要event.waitUntil在函数的开头移动调用,否则您的服务人员可能会在此期间被杀死(这就是正在发生的事情)。

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

  event.waitUntil(
    registration.pushManager.getSubscription()
    ...
  );
});
于 2016-01-22T13:12:47.913 回答