Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

UPDATE 2:

I've tried writing the code again but from a different angle.

function registerServiceWorker() {
  return navigator.serviceWorker.register('serviceworker.js')
  .then(function(registration) {
    console.log('Service worker successfully registered.');
    return registration;
  })
  .catch(function(err) {
    console.error('Unable to register service worker.', err);
  });
}


function askPermission() {
  return new Promise(function(resolve, reject) {
    const permissionResult = Notification.requestPermission(function(result) {
      resolve(result);
    });

    if (permissionResult) {
      permissionResult.then(resolve, reject);
    }
  })
  .then(function(permissionResult) {
    if (permissionResult !== 'granted') {
      throw new Error('We weren\'t granted permission.');
    }
  });
}


function subscribeUserToPush() {
  return navigator.serviceWorker.register('serviceworker.js')
  .then(function(registration) {
    const subscribeOptions = {
      userVisibleOnly: true,
      applicationServerKey: new Uint8Array("key goes here")

    };

    return registration.pushManager.subscribe(subscribeOptions);
  })
  .then(function(pushSubscription) {
    console.log("never called");
    console.log('Received PushSubscription: ', JSON.stringify(pushSubscription));
    return pushSubscription;
  });
}

registerServiceWorker();
askPermission();
subscribeUserToPush();

The last part of the command chain in subscribeUserToPush() where I have console.log("never called"); never executes and has no errors. I'm testing this in Chrome 67. I am positive that registration.pushManager.subscribe(subscribeOptions); is called.

like image 985
Cannon Moyer Avatar asked Jul 09 '18 20:07

Cannon Moyer


1 Answers

So after hours of trying different things I finally figured out the problem and it was annoyingly simple. So each time you call navigator.serviceWorker.register('serviceworker.js') you must put a / before the file name. The service worker will register just fine without the / but grabbing the subscription will fail. The examples that you find in the documentation do not include the /.

So, the code should've looked like this:

navigator.serviceWorker.register('/serviceworker.js')

Tada now it works....

like image 81
Cannon Moyer Avatar answered Oct 24 '22 08:10

Cannon Moyer