service worker show notification not working

Viewed 5478
navigator.serviceWorker.register('/service-worker.js').then((reg) => {

})



Notification.requestPermission(function(result) {
    console.log('User Choice', result);
    if (result !== 'granted') {
      console.log('No notification permission granted!');
    } else {
        navigator.serviceWorker.ready
        .then(function(swreg) {
            console.log("blaxblux");
          swreg.showNotification('Successfully subscribed!', {body:'TEST'});
        });
    }
  });

This is my code in main.js

It comes to console.log('blaxblux'), but doesn't show the notification at all. Request permission works as browser shows a popup with allow button.

What things could be the issues?

(I am using latest version of chrome)

3 Answers

I had a similar problem, but had notifications turned off on my Windows machine for Google Chrome. I went ahead and enabled notifications and they magically started working.

Settings -> System -> Notifications & Actions

Scroll down to the "Get Notifications from these Senders" section and verify "Google Chrome" (or your preferred browser) is set to "On"

Maybe this article can help https://developers.google.com/web/fundamentals/push-notifications/subscribing-a-user#requesting_permission

The API for getting permission recently changed from taking a callback to returning a Promise. The problem with this, is that we can't tell what version of the API is implemented by the current browser, so you have to implement both and handle both.

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.');
    }
  });
}
Related