Search code examples
javascriptfirefoxpush-notificationservice-workernavigator

onchange event not working for notifications permission in SW for firefox


I recently added a notification part for our web application and it's working fine on chrome and opera, but for firefox, initially, I got an error with this message:

The Notification permission may only be requested from inside a short running user-generated event handler.

So, I added a button for granting the notifications permission and now I find out there is a bigger bug; the 'onchange' event of navigator.permissions not working to activate notifications after getting permission from the user. here is my code:

self.addEventListener('activate', async () => { 
   if ('permissions' in navigator) { // inside of this if not executing on firefox
       navigator.permissions.query({ name: 'notifications' }).then(function (permissionStatus) {
           permissionStatus.onchange = function () {
            // do thing in here...
           };
      });
   }
   //...
});

Although I know 'window' is the default variable in js files, I also tried 'window.navigator' instead of 'navigator' and nothing changed.


Solution

  • Finally, I found out since we are triggering ask permission by hand and by clicking on a button, the firefox mechanism is different and we should do our onchange action as a result of the permission request promise just like below:

          Notification.requestPermission()
         .then(async result => {
            if (result === 'granted') {
               // subscribe and do stuff in here...
            }
         })
         .catch(err => {
            console.log('Error: ', err);
         });
    

    You can still use the explained onchange method for other browsers like chrome.