Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notification.requestPermission is undefined from ServiceWorker execution file. Chrome

I faced an issue where Notification.requestPermission doesn't fire from my ServiceWorker handler.

Interesting thing, that if try to use Notification.requestPermission from browser console it works fine and I have see the notification request in top of the Chrome browser window.

by: Notification.requestPermission().then(res => console.log(res)) . But the same throw me an error during execution from ServiceWorker file, like:

Uncaught TypeError: self.Notification.requestPermission is not a function

So, anyone maybe know what is wrong? I have already seen these posts on SoW:

  1. Webkit notifications requestPermission function doesn't work

  2. Desktop notifications allowing not working on chrome

But they does not solve my problem...

My SW push part of code where I use notifications:

  self.addEventListener('push', function(event) {
    console.log(self.Notification, Notification.requestPermission)
    self.Notification.requestPermission().then(res => console.log(res))

    if (Notification.permission === 'denied') {
      console.log('Permission wasn\'t granted. Allow a retry.');
     return;
    }

    if (Notification.permission === 'default') {
      console.log('The permission request was dismissed.');
      return;
    }

    console.log('The permission request is granted!');

    try {
      event.waitUntil(
        self.registration.showNotification(event && event.data && event.data.text() || 'Some Notification Here!')
      );
    } catch (e) {
      throw new Error(`Error in SW: ${e}`)
    }
  })
like image 645
Max Travis Avatar asked Oct 17 '22 08:10

Max Travis


2 Answers

Who those who're looking for an answer here it's easy - you shall run Notification.requestPermission only before DOMContentLoaded phase is finished.

Otherwise, the browser won't let you request this permission due to the finished page resourced load.

like image 58
Max Travis Avatar answered Oct 20 '22 15:10

Max Travis


Besides the accepted answer Also as @user706420 mentioned in the comments if the only use case is just to get the status of permission instead of using Notification.requestPermission() (which might have been used from the main thread to request permission for the first time when the users arrive at your app).

one can use Notification.permission to check the current status of the permission from within service worker just before showing the notification since permission can be changed at any time by the user.

Here is a snippet:

self.addEventListener('push', function(event) {
  if(Notification.permission === 'granted'){
     self.registration.showNotification()
  }
like image 36
HVenom Avatar answered Oct 20 '22 17:10

HVenom