Skip to content

Commit

Permalink
CW-firebase-messaging-for-web Fixed env issue for service worker
Browse files Browse the repository at this point in the history
  • Loading branch information
pvm-code committed Aug 16, 2024
1 parent 92e2dfc commit a71b7ca
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 127 deletions.
105 changes: 70 additions & 35 deletions public/firebase-messaging-sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,41 +7,76 @@ importScripts(
"https://www.gstatic.com/firebasejs/10.7.1/firebase-messaging-compat.js",
);

let firebaseConfig = {
apiKey: "AIzaSyDbTFuksgOkIVWDiFe_HG7-BE8X6Dwsg-0",
authDomain: "common-dev-34b09.firebaseapp.com",
databaseURL: "https://common-dev-34b09.firebaseio.com",
projectId: "common-dev-34b09",
storageBucket: "common-dev-34b09.appspot.com",
messagingSenderId: "870639147922",
appId: "1:870639147922:web:9ee954bb1dd52e25cb7f4b",
const ENV = {
LOCAL: "http://localhost:3000",
DEV: "https://web-dev.common.io",
STAGE: "https://web-staging.common.io",
PRODUCTION: "https://common.io",
};

// self.addEventListener("message", (event) => {
// console.log("--INIT_ENV", event);
// if (event.data && event.data.type === "INIT_ENV") {
// firebaseConfig = event.data.env;
// initializeFirebase();
// }
// });

// function initializeFirebase() {
if (firebaseConfig.apiKey) {
console.log("--firebaseConfig", firebaseConfig);
firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();

messaging.onBackgroundMessage((payload) => {
console.log("--notif-back", payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
data: payload.data,
icon: "/logo.png",
};

self.registration.showNotification(notificationTitle, notificationOptions);
});
const FIREBASE_CONFIG_ENV = {
DEV: {
apiKey: "AIzaSyDbTFuksgOkIVWDiFe_HG7-BE8X6Dwsg-0",
authDomain: "common-dev-34b09.firebaseapp.com",
databaseURL: "https://common-dev-34b09.firebaseio.com",
projectId: "common-dev-34b09",
storageBucket: "common-dev-34b09.appspot.com",
messagingSenderId: "870639147922",
appId: "1:870639147922:web:9ee954bb1dd52e25cb7f4b",
},
STAGE: {
apiKey: "AIzaSyBASCWJMV64mZJObeFEitLmdUC1HqmtjJk",
authDomain: "common-staging-1d426.firebaseapp.com",
databaseURL: "https://common-staging-1d426.firebaseio.com",
projectId: "common-staging-1d426",
storageBucket: "common-staging-1d426.appspot.com",
messagingSenderId: "701579202562",
appId: "1:701579202562:web:5729d8a875f98f6709571b",
},
PRODUCTION: {
apiKey: "AIzaSyAlYrKLd6KNKVkhmNEMKfb0cWHSWicCBOY",
authDomain: "common-production-67641.firebaseapp.com",
databaseURL: "https://common-production-67641.firebaseio.com",
projectId: "common-production-67641",
storageBucket: "common-production-67641.appspot.com",
messagingSenderId: "461029494046",
appId: "1:461029494046:web:4e2e4afbbeb7b487b48d0f",
},
};

let firebaseConfig = {};

switch (location.origin) {
case ENV.LOCAL:
case ENV.DEV: {
firebaseConfig = FIREBASE_CONFIG_ENV.DEV;
break;
}
case ENV.STAGE: {
firebaseConfig = FIREBASE_CONFIG_ENV.STAGE;
break;
}
case ENV.PRODUCTION: {
firebaseConfig = FIREBASE_CONFIG_ENV.PRODUCTION;
break;
}
default: {
firebaseConfig = FIREBASE_CONFIG_ENV.DEV;
break;
}
}
// }

firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();

messaging.onBackgroundMessage((payload) => {
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
data: payload.data,
icon: "/logo.png",
};

self.registration.showNotification(notificationTitle, notificationOptions);
});
Original file line number Diff line number Diff line change
@@ -1,99 +1,46 @@
import { FC, useEffect } from "react";
import { FC, useEffect, useState } from "react";
import { useSelector } from "react-redux";
import firebaseConfig from "@/config";
import { selectUser } from "@/pages/Auth/store/selectors";
import { NotificationService } from "@/services";

const NotificationsHandler: FC = () => {
const user = useSelector(selectUser());
const userId = user?.uid;
const [isRegistered, setIsRegistered] = useState(false);

// useEffect(() => {
// NotificationService.requestPermissions();
// }, []);
useEffect(() => {
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("/firebase-messaging-sw-dev.js")
.then((registration) => {
setIsRegistered(true);
return registration;
})
.catch((err) => {
console.log("ServiceWorker registration failed: ", err);
});
}
}, []);

useEffect(() => {
if (!userId) {
if (!userId && !isRegistered) {
return;
}

let unsubscribeOnMessage;
let unsubscribeLoad;
(async () => {
const hasPermissions = await NotificationService.requestPermissions();
console.log("-hasPermissions", hasPermissions);
if (hasPermissions) {
await NotificationService.saveFCMToken();

unsubscribeOnMessage = NotificationService.onForegroundMessage();

if ("serviceWorker" in navigator) {
console.log("--here");
navigator.serviceWorker
.register("/firebase-messaging-sw.js")
.then((registration) => {
console.log(
"ServiceWorker registration successful with scope: ",
registration.scope,
);
// registration.active?.postMessage({
// type: "INIT_ENV",
// env: firebaseConfig.firebase,
// });

console.log("---registration", registration);
if (registration.active) {
registration.active.postMessage({
type: "INIT_ENV",
env: firebaseConfig.firebase,
});
} else if (registration?.installing) {
registration.installing.addEventListener("statechange", () => {
if (registration?.installing?.state === "activated") {
registration.installing.postMessage({
type: "INIT_ENV",
env: firebaseConfig.firebase,
});
}
});
} else if (registration?.waiting) {
registration.waiting.addEventListener("statechange", () => {
if (registration?.waiting?.state === "activated") {
registration.waiting.postMessage({
type: "INIT_ENV",
env: firebaseConfig.firebase,
});
}
});
}
return registration;
})
.catch((err) => {
console.log("ServiceWorker registration failed: ", err);
});
unsubscribeLoad = window.addEventListener("load", () => {});
}
}
})();

// return () => {
// unsubscribeLoad && unsubscribeLoad();
// unsubscribeOnMessage && unsubscribeOnMessage();
// };
}, [userId]);

// useEffect(() => {
// console.log("--userId", userId, "--isRegistered", isRegistered);
// if (!userId || !isRegistered) {
// return;
// }

// NotificationService.saveFCMToken();

// const unsubscribe = NotificationService.onForegroundMessage();

// return unsubscribe;
// }, [userId, isRegistered]);
return () => {
unsubscribeOnMessage && unsubscribeOnMessage();
};
}, [userId, isRegistered]);

return null;
};
Expand Down
26 changes: 7 additions & 19 deletions src/services/Notification.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import firebase from "@/shared/utils/firebase";
import firebaseConfig from "@/config";
import Api from "./Api";
import { NODATA } from "dns";

enum NOTIFICATIONS_PERMISSIONS {
DEFAULT = "default",
Expand All @@ -28,7 +27,6 @@ class NotificationService {
}
const permission = await Notification.requestPermission();
if (permission === NOTIFICATIONS_PERMISSIONS.GRANTED) {
console.log('Notification permission granted.');
return true;
} else {
return false;
Expand All @@ -40,40 +38,30 @@ class NotificationService {

public saveFCMToken = async (): Promise<void> => {
try {
console.log('-hastPermissions', firebaseConfig.vapidKey);
const token = await firebase.messaging().getToken({ vapidKey: firebaseConfig.vapidKey });
if (token) {
try {
console.log("FCM Token:", token);

await Api.post(
this.endpoints.setFCMToken,
{
token,
}
);
} catch (error) {
console.error("An error occurred while retrieving token. ", error);
}
} else {
console.log("No registration token available. Request permission to generate one.");
await Api.post(
this.endpoints.setFCMToken,
{
token,
}
);
}
} catch (error) {
console.error("An error occurred while retrieving token. ", error);
}
}

public onForegroundMessage = () => {
console.log('-subscribe', firebase.messaging().onMessage);
const unsubscribe = firebase.messaging().onMessage((payload) => {
console.log('Message received. ', payload);

const { title, body } = payload.notification;
if (Notification.permission === 'granted') {
new Notification(title, {
body,
data: payload?.data,
icon: '/logo.png', // Replace with your icon
icon: "/logo.png",
});
}
});
Expand Down

0 comments on commit a71b7ca

Please sign in to comment.