javascriptfirebasefirebase-cloud-messagingservice-worker

Why I am unable to register service worker in my Firebase Vanilla JS app?


I have this JavaScript application that simply initializes and displays Firebase push notifications:

import { initializeApp } from "firebase/app";
import { getMessaging, onMessage, getToken } from "firebase/messaging";

const firebaseConfig = {
  // config
};
  
  
const vapidKey = //vapid;


console.log("Here");
// Initialize Firebase  
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
    
Notification.requestPermission().then(function(permission) { 
    console.log('permiss', permission)

    if (permission === 'granted') {
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker
            .register(new URL('./firebase-messaging-sw.js', import.meta.url), {type: 'module'} )
            .then(function (registration) {
                console.log('Registration successful, scope is:', registration.scope)

                getToken(messaging,{vapidKey})
                    .then(function (currentToken) {
                        if (currentToken) {
                            console.log("Get token:",currentToken)
                            document.getElementById("token").innerText=currentToken

                            onMessage(messaging, (payload) => {
                                console.log(payload)
                            });
                        }
                    }).catch(error => console.error(error));
            })
            .catch(function (err) {
                console.log('Service worker registration failed, error:', err)
            })
        }
    }
});

I also initialized the service worker as well:

import { initializeApp } from 'firebase/app';
import { getMessaging } from "firebase/messaging";
import { onBackgroundMessage } from 'firebase/messaging/sw'

const firebaseConfig = {
 // firebase Config
};

const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);

onBackgroundMessage(messaging, (payload) => {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);

  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background message body',
    icon: 'icon.png'
  };

  // self.registration.showNotification(notificationTitle, notificationOptions);
});

But I get the error:

Service worker registration failed, error: TypeError: ServiceWorker script at https://172.161.10.2:1234/firebase-messaging-sw.js?1715685024290 for scope https://172.161.10.2:1234/ threw an exception during script evaluation.

But I cannot find the exception upon JS.

I am using a simple parcel app to serve it:

npx parcel --https --host 0.0.0.0 --cert=/home/node/ssl/www.crt --key=/home/node/ssl/www.key src/index.html

And my html is:

<!DOCTYPE html>
<html>
    <head>
        <title>Using Push.js to Display Web Browser Notifications</title>
        <link rel="stylesheet" href="./styles.css">
    </head>
    <body>
        <h1>Display Web Browser Notifications</h1>
        <pre><code id="token"></code></pre>
        <script type="module" src="./index.js" />
    </body>
</html>

And I load the npm installed firebase:

{
  "name": "firebasedemo",
  "version": "1.0.0",
  "description": "",
  "browserslist": [
    "since 2017-06"
  ],  
  "scripts": {
    "start": "parcel src/index.html",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "UNLICENCED",
  "devDependencies": {
    "parcel": "^2.12.0",
    "process": "^0.11.10"
  },
  "dependencies": {
    "firebase": "^10.12.0"
  }
}

Solution

  • At your service worker firebase-messaging-sw.js you need to use load the getMessaging from the firebase/messaging/sw instead of the firebase/messaging.

    Thus the firebase-messaging-sw.js should be:

    import { initializeApp } from 'firebase/app';
    import { onBackgroundMessage,getMessaging } from 'firebase/messaging/sw'
    
    // rest of code
    

    Whislt the index.js (where you load the worker firebase-messaging-sw.js) should start with:

    import { initializeApp } from "firebase/app";
    import { getMessaging, onMessage, getToken, isSupported } from "firebase/messaging";