Monday 16 July 2018

Error getting PushManager Subscription - JavaScript

I've got the following code that registers a service worker and asks the user allow notifications. I'm getting an error after the user allows the push notifications where the promise returned by serviceWorkerRegistration.pushManager.getSubscription() is null. When I close the browser and force this function call again, it works without errors. I don't understand why. Here is my code:

window.vapidPublicKey = new Uint8Array([4, 45, ...]); 
if (navigator.serviceWorker) {
  navigator.serviceWorker.register('/serviceworker.js')
  .then(function(reg) {
     console.log('Service worker change, registered the service worker');
  });
}
// Otherwise, no push notifications :(
else {
  console.error('Service worker is not supported in this browser');
}

navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
  console.log("ready");
  serviceWorkerRegistration.pushManager
  .subscribe({
    userVisibleOnly: true,
    applicationServerKey: window.vapidPublicKey
  });
});



// application.js

// Let's check if the browser supports notifications
if (!("Notification" in window)) {
  console.error("This browser does not support notifications.");
}

// Let's check whether notification permissions have already been granted
else if (Notification.permission === "granted") {
  console.log("Permission to receive notifications has been granted");
}

// Otherwise, we need to ask the user for permission
else if (Notification.permission !== 'denied') {
  Notification.requestPermission(function (permission) {
    // If the user accepts, let's create a notification
    if (permission === "granted") {
      console.log("Permission to receive notifications has been granted");
      saveSubscriptionToDatabase();
    }
  });
}

function saveSubscriptionToDatabase(){

      navigator.serviceWorker.ready
      .then((serviceWorkerRegistration) => {
        console.log(serviceWorkerRegistration.pushManager.getSubscription());
        serviceWorkerRegistration.pushManager.getSubscription()
        .then((subscription) => {
          $.post("/users/save_subscription", { subscription: subscription.toJSON() });
        });
      });

}

The error:

Uncaught (in promise) TypeError: Cannot read property 'toJSON' of null
at serviceWorkerRegistration.pushManager.getSubscription.then

UPDATE:

So I added the following button:

 <input type="button" onclick="saveSubscriptionToDatabase();" value="test">

All of the JS and post request works as expected as long as I call the function from the button click but when I call it from the conditional that checks the permission state, it still fails just like before.



from Error getting PushManager Subscription - JavaScript

No comments:

Post a Comment