javascript – getSubscription返回null订阅
作者:互联网
我是服务工作者和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”,这样,如果阻塞并简单地返回,则控制即将到来.
解决方法:
最初,当用户未订阅时,getSubscription返回的promise将解析为null.您需要调用registration.pushManager.subscribe才能订阅用户(然后,下次用户访问您的站点时,getSubscription将使用非null订阅解析).
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.
标签:javascript,service-worker,push-api 来源: https://codeday.me/bug/20191008/1871101.html