简体   繁体   中英

firebase-messaging-sw.js won't allow import statement. How to use firebase onBackgroundMessage in Angular?

I'm trying to implement Firebase Messaging Service in my Angular project.

Firebase onMessage is working correctly when app is in focus but I'm unable to figure out how to use onBackgroundMessage and show a system notification to users.

I followed this Firebase Messaging Guide but unable to import onBackgroundMessage from "firebase/messaging/sw" like in the guide.

If I use import statement it says import statement can not be used outside a module.

Currently My firbase-messaging-sw.js looks like this.

importScripts("https://www.gstatic.com/firebasejs/9.1.3/firebase-app-compat.js");
importScripts("https://www.gstatic.com/firebasejs/9.1.3/firebase-messaging-compat.js");
console.log('123asd123ascd')
const app = firebase.initializeApp({
  apiKey: "AIzaSyAyGD0QIxpGieOtvEvFBzJMO5l5WnQxwEw",
  authDomain: "notifications-test-a3170.firebaseapp.com",
  projectId: "notifications-test-a3170",
  storageBucket: "notifications-test-a3170.appspot.com",
  messagingSenderId: "301382591226",
  appId: "1:301382591226:web:7646ab699982008f35df43",
  measurementId: "G-E58TMQZWLP",
  senderId: 301382591226,
});
const messaging = firebase.messaging(app);

I want my firebase-messaing-sw.js like this

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

const messaging = getMessaging();
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: '/firebase-logo.png'
  };

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

you need to export something from the file that import the firebase services. You need to include the call to onBackgroundMessage somewhere anyway, otherwise it won't run. I don't know what self refers to though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM