From 4abef3582222a40171e799ca11ecb6c22531d871 Mon Sep 17 00:00:00 2001 From: Patrick Fic Date: Wed, 22 Jul 2020 11:34:46 -0700 Subject: [PATCH] Firebase Messaging WIP to clean up service worker and implement proper notifications. Missed in last commit --- client/public/firebase-messaging-sw.js | 77 ++++++++++++++----- .../fcm-notification.component.jsx | 29 +++---- client/src/firebase/firebase.utils.js | 36 ++++++++- client/src/serviceWorker.js | 18 +---- 4 files changed, 107 insertions(+), 53 deletions(-) diff --git a/client/public/firebase-messaging-sw.js b/client/public/firebase-messaging-sw.js index 083f63d12..99c78d646 100644 --- a/client/public/firebase-messaging-sw.js +++ b/client/public/firebase-messaging-sw.js @@ -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); }); diff --git a/client/src/components/fcm-notification/fcm-notification.component.jsx b/client/src/components/fcm-notification/fcm-notification.component.jsx index 998c068de..6f3fa32fa 100644 --- a/client/src/components/fcm-notification/fcm-notification.component.jsx +++ b/client/src/components/fcm-notification/fcm-notification.component.jsx @@ -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); + }); +} diff --git a/client/src/firebase/firebase.utils.js b/client/src/firebase/firebase.utils.js index 78f6f6517..609405130 100644 --- a/client/src/firebase/firebase.utils.js +++ b/client/src/firebase/firebase.utils.js @@ -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); + }); +}); diff --git a/client/src/serviceWorker.js b/client/src/serviceWorker.js index 85bd9079b..372b6674d 100644 --- a/client/src/serviceWorker.js +++ b/client/src/serviceWorker.js @@ -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); } })