getSubscription返回null订阅

时间:2016-02-11 06:55:44

标签: javascript service-worker push-api

我是服务工作者和GAE的新手,我能够注册服务工作者但无法订阅PushManager,获得订阅null错误。 找到以下代码供参考。

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);  
  });
});

在上面的代码中,将“subscription”值变为“null”,这样,如果阻塞并简单地返回,控制就会到来。

1 个答案:

答案 0 :(得分:3)

最初,当用户未订阅时,getSubscription返回的承诺会解析为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.