getSubscription返回空订阅 [英] getSubscription returns a null subscription

查看:88
本文介绍了getSubscription返回空订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to service workers and GAE, I am able to register the service workers but not able to subscribe the PushManager, getting subscription null error. Find the below code for reference.

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块并简单地返回.

In above code getting "subscription" value as "null" inside then, so that, control is coming to if block and simply returning.

推荐答案

最初,当用户未订阅时, getSubscription 返回的承诺将解析为 null .您需要调用 registration.pushManager.subscribe 来订阅用户(然后,当用户下次访问您的网站时, getSubscription 将解析为非空值)订阅).

Initially, when the user isn't subscribed, the promise returned by getSubscription resolves to null. You need to call registration.pushManager.subscribe in order to subscribe the user (and then, the next time the user visits your site, getSubscription will resolve with a non-null subscription).

ServiceWorker食谱上有很多示例.

一个简单的例子:

// 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.

这篇关于getSubscription返回空订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆