I want to show push notification using a service worker. In the developer tools -> Application -> Service workers I have the test text "a": "test message"
, I press the push and get the following error:
serviceWorker.js:48 Uncaught (in promise) TypeError: Failed to execute
'showNotification' on 'ServiceWorkerRegistration': No notification
permission has been granted for this origin.
How can I fix this? When you click on the push button, should the notification pop up?
I want to show push notification using a service worker. In the developer tools -> Application -> Service workers I have the test text "a": "test message"
, I press the push and get the following error:
serviceWorker.js:48 Uncaught (in promise) TypeError: Failed to execute
'showNotification' on 'ServiceWorkerRegistration': No notification
permission has been granted for this origin.
How can I fix this? When you click on the push button, should the notification pop up?
Share Improve this question asked Mar 4, 2019 at 7:12 J.MichaelJ.Michael 1653 silver badges10 bronze badges2 Answers
Reset to default 5For Push messages, you need two API's setup Notification API and Push API. First things first, ask permission of the client for notification. Unless that is granted nothing works. So in your index.js/App.js place this snippet:-
function askForNPerm() {
Notification.requestPermission(function(result) {
console.log("User choice", result);
if (result !== "granted") {
console.log("No notification permission granted!");
} else {
configurePushSub();// Write your custom function that pushes your message
}
});
}
Once you are allowed with the permission, then call your Push function that has message to display.
It's Work. You also need to check if your browser has permission.
self.addEventListener('push', (event) => {
const options = {
body: 'This notification was generated from a push!',
icon: '',
data: {
dateOfArrival: Date.now(),
primaryKey: '2'
},
actions: [
{
action: 'explore', title: 'Explore this new world',
icon: ''
},
{
action: 'close', title: 'Close',
icon: ''
},
]
};
event.waitUntil(
self.registration.showNotification('Title', options)
)
});