首页 > 解决方案 > 在 chrome 中显示推送消息

问题描述

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

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

标签: javascriptreactjsservice-worker

解决方案


对于推送消息,您需要两个 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
    }
  });
}

一旦您获得许可,然后调用您的推送函数,该函数具有要显示的消息。


推荐阅读