Skip to content

Commit

Permalink
CW-firebase-messaging-for-web Update settings
Browse files Browse the repository at this point in the history
  • Loading branch information
pvm-code committed Aug 15, 2024
1 parent cd759f1 commit 6b7537e
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 41 deletions.
7 changes: 5 additions & 2 deletions public/firebase-messaging-sw.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
/* eslint-disable */
// firebase-messaging-sw.js
importScripts(
"https://www.gstatic.com/firebasejs/10.1.0/firebase-app-compat.js",
"https://www.gstatic.com/firebasejs/10.7.1/firebase-app-compat.js",
);
importScripts(
"https://www.gstatic.com/firebasejs/10.1.0/firebase-messaging-compat.js",
"https://www.gstatic.com/firebasejs/10.7.1/firebase-messaging-compat.js",
);

let firebaseConfig = {};

self.addEventListener("message", (event) => {
console.log("--INIT_ENV", event);
if (event.data && event.data.type === "INIT_ENV") {
firebaseConfig = event.data.env;
initializeFirebase();
Expand All @@ -18,11 +19,13 @@ self.addEventListener("message", (event) => {

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,
Expand Down
117 changes: 80 additions & 37 deletions src/pages/App/handlers/NotificationsHandler/NotificationsHandler.tsx
Original file line number Diff line number Diff line change
@@ -1,56 +1,99 @@
import { FC, useEffect, useState } from "react";
import { FC, useEffect } 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 [isRegistered, setIsRegistered] = useState(false);
const userId = user?.uid;

useEffect(() => {
NotificationService.requestPermissions();
}, []);

useEffect(() => {
if ("serviceWorker" in navigator) {
const unsubscribe = window.addEventListener("load", () => {
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,
});
setIsRegistered(true);
return registration;
})
.catch((err) => {
console.log("ServiceWorker registration failed: ", err);
});
});

return unsubscribe;
}
}, [setIsRegistered]);
// useEffect(() => {
// NotificationService.requestPermissions();
// }, []);

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

NotificationService.saveFCMToken();
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();
// const unsubscribe = NotificationService.onForegroundMessage();

return unsubscribe;
}, [userId, isRegistered]);
// return unsubscribe;
// }, [userId, isRegistered]);

return null;
};
Expand Down
11 changes: 9 additions & 2 deletions src/services/Notification.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
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 @@ -22,6 +23,9 @@ class NotificationService {

public requestPermissions = async (): Promise<boolean> => {
try {
if(Notification.permission === NOTIFICATIONS_PERMISSIONS.GRANTED) {
return true;
}
const permission = await Notification.requestPermission();
if (permission === NOTIFICATIONS_PERMISSIONS.GRANTED) {
console.log('Notification permission granted.');
Expand Down Expand Up @@ -60,18 +64,21 @@ class NotificationService {
}

public onForegroundMessage = () => {
return firebase.messaging().onMessage((payload) => {
console.log('-subscribe');
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,
data: payload?.data,
icon: '/logo.png', // Replace with your icon
});
}
});

return unsubscribe;
}
}

Expand Down

0 comments on commit 6b7537e

Please sign in to comment.