Home > Mobile >  Using Webpack with Firebase Messaging service worker
Using Webpack with Firebase Messaging service worker

Time:01-26

I'm using Firebase Messaging to send notifications to an Angular web app. Everything is working, using code like this in my firebase-messaging-sw.js file:

importScripts('https://www.gstatic.com/firebasejs/9.15.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.15.0/firebase-messaging-compat.js');

let firebaseConfig = { /* config here */ };
let app = firebase.initializeApp(firebaseConfig);
let messaging = firebase.messaging();

I would much prefer not to load the Firebase libraries from the CDN, so I don't have to make sure the library versions match what I'm importing in the web app (via the usual import statements from node_modules).

What seemed to be the right solution is to use Webpack to combine my service worker code above with its Firebase library dependencies, but I can't seem to get it to work.

As an initial test, I used webpack with this code:

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

let firebaseConfig = { /* config here */ };
let app = initializeApp(firebaseConfig);  
let messaging = getMessaging(app);        

I replaced my existing firebase-messaging-sw.js with the webpacked output file, but the browser output shows this error:

Uncaught (in promise) FirebaseError: Messaging: This browser doesn't support the API's required to use the Firebase SDK. (messaging/unsupported-browser).

This suggests to me that webpack is including the parts of the Firebase library intended for the browser instead of the service worker. (I am setting target to webworker in my webpack.config.js, but it doesn't seem to make a difference.)

How can I accomplish this? Is it possible with webpack?

CodePudding user response:

That's due to the fact that you're importing getMessaging from firebase/messaging:

import { getMessaging } from "firebase/messaging";

To use Firebase in a service worker you should import it from firebase/messaging/sw instead:

import { getMessaging } from "firebase/messaging/sw";
  • Related