Estoy tratando de implementar Firebase Cloud Messaging para la web usando su SDK v9, que está impulsando mucho el uso de módulos de Javascript... y necesito registrar el trabajador del servicio dentro de un componente de Vue.
El trabajador del servicio sigue gritando "no puede usar declaraciones de importación fuera de un módulo". Entonces, intenté agregar la opción {type: 'module'} a la llamada navigator.serviceWorker.register ... pero no tuve suerte. También probé los importScripts de la vieja escuela sin éxito. La pequeña cantidad de ejemplos en línea muestra <script type='module'> pero eso no tiene sentido dentro de un componente Vue, al menos por lo que entiendo.
Aquí está la totalidad del trabajador de servicio:
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) });Aquí es donde intento registrarlo, que está dentro de la sección "montada ()" de mi componente Vue:
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'); }Cualquier ayuda sería apreciada.
Puedes probarlo con este código para el SW:
importScripts('/__/firebase/9.0.1/firebase-app-compat.js'); importScripts('/__/firebase/9.0.1/firebase-messaging-compat.js'); importScripts('/__/firebase/init.js'); const messaging = firebase.messaging(); messaging.onBackgroundMessage(function(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: '/firebase-logo.png' }; self.registration.showNotification(notificationTitle, notificationOptions); });