Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getSubscription returns a null subscription

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

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

like image 737
Srinivas Avatar asked Feb 11 '16 06:02

Srinivas


1 Answers

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

There are many examples on the ServiceWorker Cookbook.

A simple example here:

// 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.
like image 86
Marco Castelluccio Avatar answered Oct 29 '22 01:10

Marco Castelluccio