Javascript 在chrome中显示推送消息

Javascript 在chrome中显示推送消息,javascript,reactjs,service-worker,Javascript,Reactjs,Service Worker,我想使用服务工作者显示推送通知。在developer tools->Application->Service workers中,我有测试文本“a”:“test message”,我按下按钮,得到以下错误: serviceWorker.js:48 Uncaught (in promise) TypeError: Failed to execute 'showNotification' on 'ServiceWorkerRegistration': No notification permiss

我想使用服务工作者显示推送通知。在developer tools->Application->Service workers中,我有测试文本
“a”:“test message”
,我按下按钮,得到以下错误:

serviceWorker.js:48 Uncaught (in promise) TypeError: Failed to execute 
'showNotification' on 'ServiceWorkerRegistration': No notification 
permission has been granted for this origin. 

我怎样才能解决这个问题?单击按钮时,是否应弹出通知?

对于推送消息,您需要两个API设置通知API推送API。 第一件事首先,请求客户允许通知。除非得到批准,否则一切都不起作用。因此,在index.js/App.js中放置以下代码段:-

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
    }
  });
}

一旦您被允许使用该权限,然后调用有消息要显示的推送功能。

就可以了。您还需要检查您的浏览器是否具有权限

 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)
    )
    });