25
loading...
This website collects cookies to deliver better user experience
import firebase from 'firebase/app';
import 'firebase/messaging';
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID",
measurementId: "YOUR MEASUREMENT ID"
};
firebase.initializeApp(firebaseConfig);
Note: The above configuration can be found from your firebase project (Under Project Settings or from Step 1)
The FCM Web interface uses Web credentials called “Voluntary Application Server Identification,” or “VAPID” keys, to authorise send requests to supported web push services.
For more information about the format of the keys and how to generate them, see Application server keys.
const messaging = firebase.messaging();
const { REACT_APP_VAPID_KEY } = process.env
const publicKey = REACT_APP_VAPID_KEY;
getToken
method that firebase provides.export const getToken = async (setTokenFound) => {
let currentToken = '';
try {
currentToken = await messaging.getToken({vapidKey: publicKey});
if (currentToken) {
setTokenFound(true);
} else {
setTokenFound(false);
}
} catch (error) {
console.log('An error occurred while retrieving token.', error);
}
return currentToken;
};
getToken
will ask the user for notification permissions, if they have not been granted. Otherwise, it returns a token or rejects the promise due to an error.getToken
After you’ve obtained the token, store it using your preferred method, in our case, we will just log in the console.
firebaseInit.js
file, so that we know the notification has receivedexport const onMessageListener = () =>
new Promise((resolve) => {
messaging.onMessage((payload) => {
resolve(payload);
});
});
onBackgroundMessage.
firebase-messaging-sw.js
service-worker file in the public folder of our react app. Add the following linesimportScripts("https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js");
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID",
measurementId: "YOUR MEASUREMENT ID"
};
firebase.initializeApp(firebaseConfig);
onBackgroundMessage
inside the service worker fileconst messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
console.log("Received background message ", payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: "/logo192.png",
};
return self.registration.showNotification(
notificationTitle,
notificationOptions
);
});
App.js
we import the file firebaseInit.js
and implement the onMessageListener
const [show, setShow] = useState(false);
const [notification, setNotification]=useState({title:"",body:""});
onMessageListener()
.then((payload) => {
setShow(true);
setNotification({
title: payload.notification.title,
body: payload.notification.body,
});
console.log(payload);
})
.catch((err) => console.log("failed: ", err));
Note: We use the useState hooks, which determine when to show the notification.
Notifications.
This component is basically responsible for getting the token from the browser.const Notifications = (props) => {
const [isTokenFound, setTokenFound] = useState(false);
console.log("Token found", isTokenFound);
useEffect(() => {
let data;
async function tokenFunc() {
data = await getToken(setTokenFound);
if (data) {
console.log("Token is", data);
}
return data;
}
tokenFunc();
}, [setTokenFound]);
return <></>;
};
export default Notifications;
getToken
function, which is defined inside firebaseInit.js
Once we get the token, we log it in the console.Note: We use the useEffect hook, since we don’t want to call the getToken repeatedly.
ReactNotificationComponent
which basically shows the notification, when the app is in foreground.import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
const ReactNotificationComponent = ({ title, body }) => {
toast.info(<Display />);
function Display() {
return (
<div>
<h4>{title}</h4>
<p>{body}</p>
</div>
);
}
return (
<ToastContainer />
);
};
App.js
index.js
. Refer link.