简体   繁体   中英

Create-react-app registerServiceWorker giving undefined at getRegistration() promise

First, it is working on PC but doesn't on a mobile device, that is my main problem.

I created a PWA using create-react-app and I'm trying to implement push notifications but seems like I get undefined at the 'reg' argument of my promise. Someone knows how to make this works? I already try to eject create-react-app but gives the same problem.

I added this code to registerServiceWorker.js :

export function displayNotification() {
  if (Notification.permission === 'granted') {
    console.log('this is showing at console when i click the button')
    navigator.serviceWorker.getRegistration().then(function(reg) {
      reg.showNotification('Hello world!');
    });
  }
}

Error:

Unhandled Rejection (TypeError): Cannot read property 'showNotification' of undefined

This issue talks about this problem but I already tried those solutions and the error is the same.

https://github.com/facebook/create-react-app/issues/2253#issuecomment-312359460

Those below are an old version that only works at browser PC, and at PWA gives a blank page when clicking the button.

My PWA: https://danilosilvadev.github.io/pwa-test/

My code: https://github.com/danilosilvadev/pwa-test/tree/master

If help me with this old version that uses an npm package called "react-web-notification": "^0.3.1" or with the code that I provided in this question that is my attempt to do manually anyway I'd be grateful.

I tested it on my computer: Chrome + Windows and it's working.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM