'TypeError: undefined is not an object (evaluating 'navigator.serviceWorker.addEventListener')

I want to use Firebase Cloud Messaging to send notifications to the users, but I am getting this error when I try to setup messageing:

TypeError: undefined is not an object (evaluating 'navigator.serviceWorker.addEventListener') at node_modules/react-native/Libraries/Core/ExceptionsManager.js:104:6 in reportException at node_modules/react-native/Libraries/Core/ExceptionsManager.js:172:19 in handleException at node_modules/react-native/Libraries/Core/setUpErrorHandling.js:24:6 in handleError at node_modules/@react-native/polyfills/error-guard.js:49:36 in ErrorUtils.reportFatalError at node_modules/metro-runtime/src/polyfills/require.js:204:6 in guardedLoadModule at Screens/Tabs/Profile/UserData.js:16:4 in UserData

This is my code:

import { initializeApp, getApps, getApp } from "firebase/app";
import {getMessaging, getToken} from 'firebase/messaging';

const firebaseConfig = {
   apiKey: "...",
   appId: "...",
   authDomain: "...",
   projectId: "...",
   messagingSenderId: "...",
   storageBucket: "...",
};

export const firebaseApp = getApps().length === 0 ? initializeApp(firebaseConfig) : getApp(); 
const messaging = getMessaging(firebaseApp);


getToken(messaging, { vapidKey: '...' }).then((currentToken) => {
    if (currentToken) {
      // Send the token to your server and update the UI if necessary
      // ...
    } else {
      // Show permission request UI
      console.log('No registration token available. Request permission to generate one.');
      // ...
    }
  }).catch((err) => {
    console.log('An error occurred while retrieving token. ', err);
    // ...
  });

I have generated key on Firebase Cloud Messaging



Solution 1:[1]

I just ran into this issue myself, both scenarios were on iOS--not sure if this happens more broadly or not. (I could not duplicate on Android.)

  1. From Safari on iOS: Accessing my dev box over my local network via HTTP (no TLS) throws this error.
  2. From the Facebook browser on iOS (which I assume uses some sort of Safari WebView component): accessing a site in production over HTTPS that tries to call getMessaging() from the Firebase SDK throws this error.

You would think that the Firebase SDK would either gracefully handle this case or provide explicit instructions in the docs on how to gracefully degrade the experience in unsupported browsers, but I couldn't find any mention of the subject.

I solved it like this:

let messaging;
try {
    messaging = getMessaging();
} catch (err) {
    console.error('Failed to initialize Firebase Messaging', err);
}

While this won't allow you to use Firebase Messaging on unsupported browsers, at least your app/site won't be completely unusable. On supported browsers, things should work normally.

Hope this helps!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matt Hamann