Firebase Messaging Error Unable to register the default service worker

I am having the file firebase-messaging-sw.js, which is visible in the networks, logging message in the console too. But sill I am getting :

An error occurred while retrieving token.  FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script. (messaging/failed-serviceworker-registration).
    at https://www.gstatic.com/firebasejs/6.6.1/firebase-messaging.js:1:29909:

I have tried to check the console and also debug, but not sure what is error is.

the firebase-messaging-sw.js file contains:

importScripts('https://www.gstatic.com/firebasejs/4.1.3/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.1.3/firebase-messaging.js');
console.log("in sw page");

the index.html is having:

firebase.initializeApp({
                apiKey: "XXXXXX",
                authDomain: "XXXX-XXXXX.firebaseapp.com",
                databaseURL: "XXXXXXX",
                projectId: "XXXXXX",
                storageBucket: "",
                messagingSenderId: "XXXXXXX",
                appId: "XXXXX"
              });
                //  // Initialize Firebase
                const messaging = firebase.messaging();
            Notification.requestPermission().then((permission) => {
              if (permission === 'granted') {
                navigator.serviceWorker.register('firebase-messaging-sw.js')
                console.log('Notification permission granted.');
                    messaging.getToken().then((currentToken) => {
                      if (currentToken) {
                        console.log(currentToken);
                      } else {
                        // Show permission request.
                        console.log('No Instance ID token available. Request permission to generate one.');

                      }
                    }).catch((err) => {
                      console.log('An error occurred while retrieving token. ', err);
                    });
              } else {
                console.log('Unable to get permission to notify.');
              }
            });

I’m expecting to get a token once the user clicks on allow. What could be the reason? And any resolution for it?

Answer

create firebase-messaging-sw.js in your root folder and paste the code in it.

if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('../firebase-messaging-sw.js')
  .then(function(registration) {
    console.log('Registration successful, scope is:', registration.scope);
  }).catch(function(err) {
    console.log('Service worker registration failed, error:', err);
  });
}

Leave a Reply