0

我正在使用带有 PWA 的 create-react-app 并且无法使用通知 api :(

这个错误:

Cannot read property 'showNotification' of undefined

我的代码

Notification.requestPermission(function(status) {
    console.log("Notification permission status:", status);
  });

  async function displayNotification() {
    if (Notification.permission === "granted") {
       await navigator.serviceWorker.getRegistration().then(reg => {
         reg.showNotification("Go go")
       });
    }
  }

我不明白错误

4

1 回答 1

3

你不能既 await 又使用 then 。你只能在 promise 上使用 then。如果你等待,你就会兑现你的承诺。

你可以这样做:

async function displayNotification() {
  if (Notification.permission === "granted") {
     const reg = await navigator.serviceWorker.getRegistration();
     reg.showNotification("Go go");
  }
}

或者 :

function displayNotification() {
  if (Notification.permission === "granted") {
     navigator.serviceWorker.getRegistration().then(reg => {
       reg.showNotification("Go go");
     });
  }
}
于 2019-10-23T18:39:47.693 回答