Firebase Messaging WIP to clean up service worker and implement proper notifications.

Missed in last commit
This commit is contained in:
Patrick Fic
2020-07-22 11:34:46 -07:00
parent 8f8c26af54
commit 4abef35822
4 changed files with 107 additions and 53 deletions

View File

@@ -28,29 +28,70 @@ firebase.initializeApp({
const messaging = firebase.messaging();
//Handles Background Messages
// messaging.setBackgroundMessageHandler(function (payload) {
// console.log("backgroundMessageHandler", payload);
// const promiseChain = clients
// .matchAll({
// type: "window",
// includeUncontrolled: true,
// })
// .then((windowClients) => {
// for (let i = 0; i < windowClients.length; i++) {
// const windowClient = windowClients[i];
// console.log("[fbmsw] Posting Paylout to window client.");
// windowClient.postMessage(payload);
// }
// })
// .then(() => {
// console.log("[fbmsw] Showing notification.");
// return registration.showNotification(JSON.stringify(payload));
// });
// return promiseChain;
// });
// messaging.onMessage((payload) => {
// console.log("Message received. ", payload);
// // ...
// });
messaging.setBackgroundMessageHandler(function (payload) {
console.log("backgroundMessageHandler", payload);
const promiseChain = clients
.matchAll({
type: "window",
includeUncontrolled: true,
})
.then((windowClients) => {
for (let i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
windowClient.postMessage(payload);
}
})
.then(() => {
return registration.showNotification(JSON.stringify(payload));
});
return promiseChain;
console.log(
"**********[firebase-messaging-sw.js] Received background message ",
payload
);
// Customize notification here
const notificationTitle = "Background Message Title";
const notificationOptions = {
body: payload.notification.body + "FROM SW",
icon: "logo240.png",
};
return self.registration.showNotification(
notificationTitle,
notificationOptions
);
});
// self.addEventListener("message", (message) => {
// const { payload } = message.data.firebaseMessaging;
// navigator.serviceWorker.getRegistration().then((registration) =>
// registration.showNotification(payload.notification.title, {
// body: payload.notification.body + "FROM SW",
// icon: "logo240.png",
// badge: "logo240.png",
// actions: [
// {
// action: "respond",
// title: "Respond",
// },
// ],
// })
// );
// });
//Handles the notification getting clicked.
self.addEventListener("notificationclick", function (event) {
// do what you want
// ...
console.log("SW notificationclick", event);
});

View File

@@ -31,23 +31,6 @@ class FcmNotificationComponent extends Component {
console.log("Unable to get permission to notify.", err);
logImEXEvent("fcm_permission_denied", { message: err });
});
navigator.serviceWorker.addEventListener("message", (message) => {
const { payload } = message.data.firebaseMessaging;
navigator.serviceWorker.getRegistration().then((registration) =>
registration.showNotification(payload.notification.title, {
body: payload.notification.body,
icon: "logo240.png",
badge: "logo240.png",
actions: [
{
action: "respond",
title: "Respond",
},
],
})
);
});
}
render() {
@@ -59,3 +42,15 @@ export default connect(
mapStateToProps,
mapDispatchToProps
)(withApollo(FcmNotificationComponent));
//Firebase Service Worker Register
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("/firebase-messaging-sw.js")
.then(function (registration) {
console.log("**********FCM Registration successful, scope is:", registration.scope);
})
.catch(function (err) {
console.log("**********FCM Service worker registration failed, error:", err);
});
}

View File

@@ -24,8 +24,6 @@ export const getCurrentUser = () => {
});
};
export const updateCurrentUser = (userDetails) => {
return new Promise((resolve, reject) => {
const unsubscribe = auth.onAuthStateChanged((userAuth) => {
@@ -42,9 +40,9 @@ try {
messaging = firebase.messaging();
// Project Settings => Cloud Messaging => Web Push certificates
messaging.usePublicVapidKey(process.env.REACT_APP_FIREBASE_PUBLIC_VAPID_KEY);
console.log("Firebase Messaging initialized successfully.");
console.log("**********[FCM UTIL] FCM initialized successfully.");
} catch {
console.log("Firebase Messaging is likely unsupported.");
console.log("**********[FCM UTIL] Firebase Messaging is likely unsupported.");
}
export { messaging };
@@ -62,3 +60,33 @@ export const logImEXEvent = (eventName, additionalParams, stateProp = null) => {
};
analytics.logEvent(eventName, eventParams);
};
messaging.onMessage((payload) => {
console.log("**********UTILS Message received. ", payload);
// [START_EXCLUDE]
// Update the UI to include the received message.
//appendMessage(payload);
// [END_EXCLUDE]
});
messaging.onTokenRefresh(() => {
messaging
.getToken()
.then((refreshedToken) => {
console.log("**********Token refreshed.");
// Indicate that the new Instance ID token has not yet been sent to the
// app server.
// setTokenSentToServer(false);
// // Send Instance ID token to app server.
// sendTokenToServer(refreshedToken);
// // [START_EXCLUDE]
// // Display new Instance ID token and clear UI of all previous messages.
// resetUI();
// [END_EXCLUDE]
})
.catch((err) => {
console.log("**********Unable to retrieve refreshed token ", err);
// showToken("Unable to retrieve refreshed token ", err);
});
});

View File

@@ -52,20 +52,6 @@ export function register(config) {
}
});
}
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("/firebase-messaging-sw.js")
.then(function (registration) {
console.log(
"FCM Registration successful, scope is:",
registration.scope
);
})
.catch(function (err) {
console.log("FCM Service worker registration failed, error:", err);
});
}
}
function registerValidSW(swUrl, config) {
@@ -114,6 +100,7 @@ function registerValidSW(swUrl, config) {
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
console.log("Seeing if service worker cna be found.");
fetch(swUrl)
.then((response) => {
// Ensure service worker exists, and that we really are getting a JS file.
@@ -123,6 +110,7 @@ function checkValidServiceWorker(swUrl, config) {
(contentType != null && contentType.indexOf("javascript") === -1)
) {
// No service worker found. Probably a different app. Reload the page.
console.log("No service worker found. Unregistering.");
navigator.serviceWorker.ready.then((registration) => {
registration.unregister().then(() => {
window.location.reload();
@@ -130,6 +118,8 @@ function checkValidServiceWorker(swUrl, config) {
});
} else {
// Service worker found. Proceed as normal.
console.log("Service worker found. Registering.");
registerValidSW(swUrl, config);
}
})