GetSubscription returns a zero subscription

I am new to service and GAE, I can register service workers, but I can not subscribe to PushManager, receiving a zero subscription error. Find the code below 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); }); }); 

In the above code, the value of "subscription" becomes "zero" inside, so control comes to the block and just returns.

+3
javascript push-api service-worker
source share
1 answer

Initially, when a user does not subscribe, the promise returned by getSubscription is resolved null . You need to call registration.pushManager.subscribe to subscribe to the user (and then, the next time the user visits your site, getSubscription will be allowed with a non-empty subscription).

There are many examples in the ServiceWorker Kitchenbook .

A simple example:

 // Use the PushManager to get the user 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
source share

All Articles