最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Show push message in chrome - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 5

For 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)
    )
    });
发布评论

评论列表(0)

  1. 暂无评论