Here is my whole code:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.16.0/firebase-app.js";
import { getMessaging, getToken } from "https://www.gstatic.com/firebasejs/9.16.0/firebase-messaging.js";
//This data is filled correctly just clearing it here for the question
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "t",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
const bbFirebase = initializeApp(firebaseConfig);
const messaging = getMessaging();
// Add the public key generated from the console here.
getToken(messaging, { vapidKey: 'I_HAVE_PLACED_VALID_KEY_HERE' }).then((currentToken) => {
if (currentToken) {
console.log("TOKEN: " + currentToken);
} else {
// Show permission request UI
console.log('No registration token available. Request permission to generate one.');
// ...
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
// ...
});
messaging.onBackgroundMessage((payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: '/firebase-logo.png'
};
self.registration.showNotification(notificationTitle,
notificationOptions);
});
function requestPermission() {
console.log('Requesting permission...');
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
// TODO(developer): Retrieve a registration token for use with FCM.
// In many cases once an app has been granted notification permission,
// it should update its UI reflecting this.
resetUI();
} else {
console.log('Unable to get permission to notify.');
}
});
}
So when I execute this code I can generate a token. I see the token clearly and all good there. However I have this error:
Uncaught TypeError: messaging.onBackgroundMessage is not a function
at firebase.js:31:11
Any idea why I can this error and how can I at least console.log()
print the incoming notifications?
2
Answers
The
onBackgroundMessage()
is a top level function just likegetToken()
in the new functional syntax imported fromfirebase/messaging/sw
as mentioned in the documentation.I´m having trouble with this too but if you paste this code in firebase-messaging-sw.js and that file is in the root of firebase hosting it works.