I'm attempting to implement Firebase Cloud Messaging for the web using their v9 SDK, which is heavily pushing using Javascript modules... and I need to register the service worker inside of a Vue component.
The service worker keeps screaming "you cannot use import statements outside of a module". So, I tried adding the {type: 'module'} option to the navigator.serviceWorker.register call... but no luck. I also tried the old-school importScripts to no avail. The small number of examples online show <script type='module'> but that makes no sense inside of a Vue component, at least from what I understand.
Here's the entirety of the service worker:
import { fbConfig } from "/js/firebase/firebase-config.js";
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js"
import { getMessaging, onBackgroundMessage } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-messaging-sw.js"
// Create the instance of Firebase & Messaging
const fbApp = initializeApp(fbConfig)
const messaging = getMessaging(fbApp);
onBackgroundMessage(messaging, (payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
const notificationTitle = payload.message.notification.title;
const notificationOptions = payload.message.notification.body;
let outcome = self.registration.showNotification(
notificationTitle,
notificationOptions
);
console.log('[firebase-messaging-sw.js] showNotification outcome', outcome)
});
Here's where I'm attempting to register it, which is inside of the "mounted()" section of my Vue component:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register(
'/firebase-messaging-sw.js', {
type: 'module'
})
.then(reg => {
console.log(`Service Worker Registration (Scope: ${reg.scope})`);
})
.catch(error => {
const msg = `Service Worker Error (${error})`;
console.error(msg);
});
} else {
// happens when the app isn't served over HTTPS or if the browser doesn't support service workers
console.warn('Service Worker not available');
}
Any help would be appreciated.