event.waitUntil throws an error when called in a push event listener

3.6k Views Asked by At

I'm getting error in my service-worker.js, when it receive notification from 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)
      })
    })
  });
});

With the above code, I'm able to finish gcm chrome web notification implementation, but I'm getting a error in console.

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

There are 1 best solutions below

1
On

You need to move the event.waitUntil call at the beginning of the function, otherwise your service worker could be killed in the meantime (which is what's happening).

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

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