Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service worker register then - Undefined is not a function

I use default React code for registering service worker. I have reports in bugsnag that some users are getting TypeError: undefined is not a function on the line .then(registration => { inside registerValidSW.

For me it is working but for some probably not. I did not find where could be a problem.

Could you help me with this?

export function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
  return;
}

window.addEventListener('load', () => {
  const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

  if (isLocalhost) {
    .......
  } else {
    registerValidSW(swUrl);
  }
});
}
}

function registerValidSW(swUrl) {
 navigator.serviceWorker
.register(swUrl)
.then(registration => {
  registration.onupdatefound = () => {
    const installingWorker = registration.installing;
    if (installingWorker == null) {
      return;
    }
    installingWorker.onstatechange = () => {
      ...
    };
  };
})
.catch(error => {
  console.error('Error during service worker registration:', error);
});
}
like image 401
pospichalales Avatar asked Feb 03 '19 09:02

pospichalales


1 Answers

Serviceworker and its methods including register are supported on all latest browsers excluding IE.

It has been noticed that even when serviceWorker is accessible in navigator, property register is not present which should always return a promise. Chromium bug for the same.

For now, you could avoid this issue by adding the following check:

'serviceWorker' in navigator && 'register' in navigator.serviceWorker
like image 153
mappie Avatar answered Sep 29 '22 10:09

mappie