当前位置: 代码迷 >> JavaScript >> 在Chrome中显示推送消息
  详细解决方案

在Chrome中显示推送消息

热度:253   发布时间:2023-06-07 13:48:36.0

我想使用服务人员显示推送通知。 在开发人员工具->应用程序->服务人员中,我得到了测试文本"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. 

我怎样才能解决这个问题? 当您单击按钮时,通知应该弹出吗?

对于Push消息,您需要两个API的设置Notification APIPush 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
    }
  });
}

一旦获得许可,就可以调用带有消息显示的Push函数。

是工作。 您还需要检查浏览器是否具有权限。

 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)
    )
    });
  相关解决方案