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

在上面的代码中,然后将“订阅”值设为“null”,这样,控制就进入了 if 块并简单地返回。

4

1 回答 1

7

最初,当用户未订阅时,由返回的承诺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.
于 2016-02-11T10:20:56.917 回答