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:
Webkit notifications requestPermission function doesn't work
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}`)
}
})
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.
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With