getSubscription返回了一个空的订阅。

6

我对服务工作者和GAE还很陌生,虽然能够注册服务工作者,但无法订阅PushManager,返回订阅为空的错误。以下是参考代码。

serviceWorkerRegistration.pushManager.getSubscription()  
  .then(function(subscription) {  
    var pushButton = document.querySelector('.js-push-button');  
    pushButton.disabled = false;

    if (!subscription) {  
      console.log('subscription error '); 
      return;  
    }
    console.log('subscriptioned ');

    // Keep your server in sync with the latest subscriptionId
    sendSubscriptionToServer(subscription);

    // Set your UI to show they have subscribed for  
    // push messages  
    pushButton.textContent = 'Disable Push Messages';  
    isPushEnabled = true;  
  })  
  .catch(function(err) {  
    console.warn('Error during getSubscription()', err);  
  });
});

在上面的代码中,在“then”内获取到的“subscription”值为“null”,因此,控制权转移到if语句块并直接返回。
1个回答

8
起初,当用户未订阅时,由getSubscription返回的promise将解析为null。您需要调用registration.pushManager.subscribe来订阅用户(然后,下次用户访问您的站点时,getSubscription将解析为非空订阅)。
ServiceWorker Cookbook上有许多示例。
这里是一个简单的示例:
// Use the PushManager to get the user's subscription to the push service.
serviceWorkerRegistration.pushManager.getSubscription()
.then(function(subscription) {
  // If a subscription was found, return it.
  if (subscription) {
    return subscription;
  }

  // Otherwise, subscribe the user (userVisibleOnly allows to specify
  // that we don't plan to send notifications that don't have a
  // visible effect for the user).
  return serviceWorkerRegistration.pushManager.subscribe({
    userVisibleOnly: true
  });
})
.then(function(subscription) {
  // Here you can use the subscription.

3
可以将其简化为 registration.pushManager.subscribe(...).then(subscription => ...)。如果已经存在订阅,则 subscribe() 将返回现有的订阅,因此不需要先调用 getSubscription() - Jeff Posnick
1
这在这种情况下非常有用,尽管有时如果订阅已经存在,您可能需要采取不同的行动。 - Marco Castelluccio
感谢Jeff Posnick,在进行了上述更改后,现在本地主机中一切正常。但是当部署到GAE时,我遇到了以下错误:“注册失败-未提供发送者ID”。 - Srinivas
您需要在Google开发者控制台上创建一个项目,从那里获取一些密钥(https://developers.google.com/web/fundamentals/getting-started/push-notifications/step-04),然后您需要创建一个包含`gcm_sender_id`值的Web应用程序清单,该值是来自开发者控制台的项目编号。另请参阅https://developer.mozilla.org/en-US/docs/Web/API/Push_API/Using_the_Push_API#Extra_steps_for_Chrome_support。 - Marco Castelluccio

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