'This method is available in a service worker context

I was trying to implement Firebase Web Push Notifications on my website. I've been trying to work with firebase (Web version 9)

I'm using version: 9.8.1

When implementing the onBackgroundMessage, I got the following:

onBackgroundMessage.ts:33 Uncaught FirebaseError: Messaging: This method is available in a service worker context. (messaging/only-available-in-sw).
    at onBackgroundMessage$1 (onBackgroundMessage.ts:33:25)
    at onBackgroundMessage (api.ts:170:10)

Can someone help

Below is what I've written.

 <script type="module">
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-app.js";
    import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-analytics.js";
    import { getToken, onMessage } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-messaging.js";
    import { getMessaging,onBackgroundMessage } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-messaging-sw.js";


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

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


getToken(messaging, { vapidKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' }).then((currentToken) => {
              if (currentToken) {
                console.log(currentToken);
              } else {
                alert('No registration token available. Request permission to generate one');    
              }
        }).catch((err) => {
            console.log('An error occurred while retrieving token. ', err);
        });


    onMessage(messaging, (payload) => {
      console.log('Message received. ', payload);
    });


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

    if (!(self.Notification && self.Notification.permission === 'granted')) {
        return;
    }
   
    self.registration.showNotification(payload.data.title, {
        body: payload.data.body,
        icon:  'icon-512x512.png',
        badge: '/favicon.ico',
        tag: 'renotify',
        renotify: true,
    })
    .then(() => self.registration.getNotifications())
    .then(notifications => {
        setTimeout(() => notifications.forEach(notification => notification.close()), 3000);
    });

});




</script>

What I've done wrong?



Sources

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

Source: Stack Overflow

Solution Source