React JS 및 Firebase를 사용한 푸시 알림
19417 단어 javascriptfirebasereactwebdev
오늘 우리는 Firebase에 설정된 푸시 알림을 반응 앱으로 보내려고 노력할 것입니다.
Firebase 프로젝트 만들기
Firebase에서 새 프로젝트를 생성하고 아래와 같이 중요한 정보가 모두 포함된 firebaseConfig 변수를 생성해 보겠습니다.

이제 React 앱 >> src 디렉터리에서 firebase-config.js 파일을 만들고 다음 코드를 추가합니다.
import { initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_BUCKET_ID",
messagingSenderId: "YOUR_SENDER_ID",
appId: "YOUR_APP_ID",
measurementId: "YOUR_M_ID",
};
// Initialize Firebase
export const firebase = initializeApp(firebaseConfig);
이제 firebase에서 알림을 생성하는 데 도움이 되는 반응 앱에서 토큰을 생성해야 합니다.
이를 위해 반응 앱> firebase-config.js에 다음 메소드를 추가하십시오.
import { initializeApp } from "firebase/app";
import {getMessaging,getToken, onMessage} from 'firebase/messaging';
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_BUCKET_ID",
messagingSenderId: "YOUR_SENDER_ID",
appId: "YOUR_APP_ID",
measurementId: "YOUR_M_ID",
};
// Initialize Firebase
export const firebase = initializeApp(firebaseConfig);
const messaging = getMessaging();
export const requestForToken = () => {
return getToken(messaging, { vapidKey: "YOUR_VAPID_KEY" })
.then((currentToken) => {
if (currentToken) {
console.log('current token for client: ', currentToken);
// Perform any other neccessary action with the token
} else {
// Show permission request UI
console.log('No registration token available. Request permission to generate one.');
}
})
.catch((err) => {
console.log('An error occurred while retrieving token. ', err);
});
};
export const onMessageListener = () =>
new Promise((resolve) => {
onMessage(messaging, (payload) => {
resolve(payload);
});
});
위 코드의 vapid_key는 프로젝트 >> 클라우드 메시징 섹션 >> 웹 구성 섹션의 Firebase 콘솔로 이동하여 아래와 같이 키 쌍을 생성하여 생성됩니다.

그런 다음 '테스트 메시지 보내기' 버튼을 클릭하고 반응 앱에서 생성된 토큰을 여기에 추가합니다.
반응 앱에서 코드를 완료하려면 반응 앱으로 다시 이동하여 Notifications 폴더를 만들고 여기서 Notifications.js 파일을 만들고 아래와 같이 firebase-config.js에서 requestToken 메서드를 호출합니다.
import React, {useState, useEffect} from 'react'
import toast, { Toaster } from 'react-hot-toast';
import { requestForToken, onMessageListener } from '../../firebase-config';
const Notification = () => {
const [notification, setNotification] = useState({title: '', body: ''});
const notify = () => toast(<ToastDisplay/>);
function ToastDisplay() {
return (
<div>
<p><b>{notification?.title}</b></p>
<p>{notification?.body}</p>
</div>
);
};
useEffect(() => {
if (notification?.title ){
notify()
}
}, [notification])
requestForToken();
onMessageListener()
.then((payload) => {
setNotification({title: payload?.notification?.title, body: payload?.notification?.body});
})
.catch((err) => console.log('failed: ', err));
return (
<Toaster/>
)
}
export default Notification
프런트 엔드에 알림을 표시하기 위해 'react-hot-toast' 라이브러리를 사용했습니다.
이제 반응 앱을 실행하면 아래와 같이 firebase/notification/compose의 'FCM 등록 토큰 추가' 필드에 복사/붙여넣기해야 하는 토큰이 콘솔에 생성된 것을 볼 수 있습니다.

테스트 버튼을 클릭하면 반응 앱에 알림이 팝업됩니다.
앱의 백그라운드에서 실행될 서비스 작업자를 만들려면 다음 코드를 추가할 앱의 public 폴더에 firebase-messaging-sw.js 파일을 만들어야 합니다.
// Scripts for firebase and firebase messaging
// eslint-disable-next-line no-undef
importScripts("https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js");
// eslint-disable-next-line no-undef
importScripts("https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js");
// Initialize the Firebase app in the service worker by passing the generated config
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_BUCKET_ID",
messagingSenderId: "YOUR_SENDER_ID",
appId: "YOUR_APP_ID",
measurementId: "YOUR_M_ID",
};
// eslint-disable-next-line no-undef
firebase.initializeApp(firebaseConfig);
// Retrieve firebase messaging
// eslint-disable-next-line no-undef
const 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",
};
// eslint-disable-next-line no-restricted-globals
return self.registration.showNotification(
notificationTitle,
notificationOptions
);
});
이제 Firebase에서 테스트 메시지를 만들 수 있으며 반응 앱에 표시됩니다.
행복한 코딩...
Reference
이 문제에 관하여(React JS 및 Firebase를 사용한 푸시 알림), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/nasreenkhalid/push-notifications-with-react-js-and-firebase-502m텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)