I've successfully been able to establish FCM in my Flutter web app and FirebaseMessaging.onMessage
is working fine, but when receiving a message while my app is in the background I have this in the FirebaseFlutter docs: Right now, all web background code must be executed in the JavaScript Service Worker file.
So I want to pass Firebase notification data m.data.type
and m.data.id
to my Flutter app to be able to handle the events.
I can't load my firebase-service-worker in a script Firebase messaging importScripts is not defined
I can't use window because my code doesn't run in the browser. (self is not passing the data).
importScripts("https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/8.6.1/firebase-messaging.js");
firebase.initializeApp({
apiKey: "key",
authDomain: "authDomain",
projectId: "id",
storageBucket: "",
messagingSenderId: "",
appId: "1::",
measurementId: "G-",
});
var notificationClick = false;
clients
.matchAll({ type: "window", includeUncontrolled: true })
.then(function (clientList) {
console.log(clientList);
for (var client of clientList) {
client.postMessage({
msg: "Hey I just got a fetch from you!",
});
client.state = {
type: "type",
id: "id",
};
}
});
const messaging = firebase.messaging();
messaging.onBackgroundMessage((m) => {
console.log(notificationClick);
var type = m.data.type;
var id = m.data.id;
if (m.data.type == "NewOrder") {
console.log(m.data.type);
console.log(m.data.id);
}
if (m.data.type == "UpdateOrder") {
console.log(m.data.type);
console.log(m.data.id);
}
if (m.data.type == "NewOrderTab") {
console.log(m.data.type);
console.log(m.data.id);
}
if (m.data.type == "UpdateOrderTab") {
console.log(m.data.type);
console.log(m.data.id);
}
if (m.data.type == "NewTable") {
console.log(m.data.type);
console.log(m.data.id);
}
if (m.data.type == "UpdateTable") {
console.log(m.data.type);
console.log(m.data.id);
}
const notificationTitle = m.data.title;
const notificationOptions = {
body: m.data.type,
type: m.data.type,
id: m.data.id,
};
console.log(notificationOptions);
self.state = {
type: type,
id: id,
};
// window.state = {
// type: type,
// id: id,
// };
clients
.matchAll({ type: "window", includeUncontrolled: true })
.then(function (clientList) {
console.log(clientList);
// No match by default
var matchFound = false;
// Traverse clients list
for (var client of clientList) {
client.postMessage({
msg: "Hey I just got a fetch from you!",
});
client.state = {
type: type,
id: id,
};
}
});
return self.registration.showNotification(
notificationTitle,
notificationOptions
);
});
self.addEventListener("notificationclick", function (event) {
notificationClick = true;
event.waitUntil(console.log(notificationClick));
});