event.waitUntil在推送事件侦听器中调用时抛出错误

时间:2016-01-22 10:02:44

标签: service-worker web-push push-api

我收到来自GCM的通知后,我的service-worker.js收到错误

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

1 个答案:

答案 0 :(得分:3)

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

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

  event.waitUntil(
    registration.pushManager.getSubscription()
    ...
  );
});