无法执行' waitUntil' on' ExtendableEvent'

时间:2016-04-12 11:08:28

标签: javascript notifications push-notification service-worker

我需要chrome注册ID将其作为参数发送给API调用,因此我可以获取与注册ID相对应的消息。我的代码如下:

self.addEventListener('push', function(event) {

var apiPath = 'http://localhost/api/v1/notification/getNotification?regId=';
event.waitUntil(registration.pushManager.getSubscription().then(function (subscription){
    apiPath = apiPath + subscription.endpoint.split("/").slice(-1);
    event.waitUntil(fetch(apiPath).then(function(response){
        if(response.status !== 200){
            console.log("Problem Occurred:"+response.status);
            throw new Error();
        }
        return response.json().then(function(data){
            var title = data.title;
            var message = data.body;
            var icon = data.icon;
            var tag = data.tag;
            var url = data.url;
            return self.registration.showNotification(title,{
               body: message,
               icon: icon,
               tag: tag,
               data: url
            });
        })
    }).catch(function(err){
        var title = 'Notification';
        var message = 'You have new notifications';
        return self.registration.showNotification(title,{
               body: message,
               icon: '/images/Logo.png',
               tag: 'Demo',
               data: 'http://www.google.com/'
            });
    })
    )
}));
return;
});

我使用上述代码得到的错误是:

未捕获(在承诺中)DOMException:

  

无法执行' waitUntil' on' ExtendableEvent':事件处理程序已经完成。(...)   以及额外的通知'该网站已在后台更新'。   现在,即使我在event.waitUntil部分之前移除了fetch(apiPath),我仍然会收到额外的通知。

请帮我找到解决方案。

P.S:Chrome Push Notification: This site has been updated in the background的问题似乎对我的情况有用。

1 个答案:

答案 0 :(得分:3)

您不需要多次致电event.waitUntil。你只需要调用一次并传递一个承诺,事件的生命周期将延长,直到承诺得到解决。

self.addEventListener('push', function(event) {
  var apiPath = 'http://localhost/api/v1/notification/getNotification?regId=';

  event.waitUntil(
    registration.pushManager.getSubscription()
    .then(function(subscription) {
      apiPath = apiPath + subscription.endpoint.split("/").slice(-1);

      return fetch(apiPath)
      .then(function(response) {
        if (response.status !== 200){
          console.log("Problem Occurred:"+response.status);
          throw new Error();
        }

        return response.json();
      })
      .then(function(data) {
        return self.registration.showNotification(data.title, {
          body: data.body,
          icon: data.icon,
          tag: data.tag,
          data: data.url,
        });
      })
      .catch(function(err) {
        return self.registration.showNotification('Notification', {
          body: 'You have new notifications',
          icon: '/images/Logo.png',
          tag: 'Demo',
          data: 'http://www.google.com/'
        });
      });
    })
  );
});
相关问题