Firebase 및 React로 푸시 알림을 보내는 방법
30264 단어 reactwebdevjavascriptfirebase
우리가 구축하는 것
전체 코드를 가져옵니다here.
Firebase 프로젝트 만들기
Continue to console
React 앱에 Firebase 추가
npm i -g firebase-tools
npx degit https://github.com/jeremytenjo/starter-demo.git firebase-messaging-with-react && cd firebase-messaging-with-react && npm i && npm run dev
npm i firebase @useweb/use-firebase-messaging @useweb/use-firebase
firebase init hosting
Use an existing project
tut-push-notifications (tut-push-notifications)
? What do you want to use as your public directory? public
? Configure as a single-page app (rewrite all urls to /index.html)? Yes
? Set up automatic builds and deploys with GitHub? No
firebase.json
및 .firebaserc
gcm_sender_id
속성을 manifest.json
에 추가합니다. 변경하지 않고 그대로 아래 값을 삽입하십시오.{
"gcm_sender_id": "103953800507"
}
/* eslint-disable no-undef */
importScripts('https://www.gstatic.com/firebasejs/8.6.8/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/8.6.8/firebase-messaging.js')
const firebaseConfig = undefined // firebaseConfig is required
firebase.initializeApp(firebaseConfig)
const messaging = firebase.messaging()
messaging.onBackgroundMessage((payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload)
const notificationTitle = payload.notification.title
const notificationOptions = {
body: payload.notification.body,
icon: payload.notification.icon || payload.notification.image,
}
self.registration.showNotification(notificationTitle, notificationOptions)
})
self.addEventListener('notificationclick', (event) => {
if (event.action) {
clients.openWindow(event.action)
}
event.notification.close()
})
firebaseConfig = undefined
의 firebase-messaging-sw.js
를 Firebase 구성으로 바꿉니다. Firebase 콘솔의 Project settings
에서 찾습니다. src/services/Firebase/Firebase.tsx
하고 다음 코드를 추가합니다. 나중에 사용할 @useweb/use-firebase
패키지에 필요한 데이터를 전달하기 위해 @useweb/use-firebase-messaging
패키지를 사용하고 있습니다.import React from 'react'
import { FirebaseProvider } from '@useweb/use-firebase'
import { initializeApp } from 'firebase/app'
import { getMessaging } from 'firebase/messaging'
const firebaseConfig = undefined // firebaseConfig is required
const firebaseApp = initializeApp(firebaseConfig)
const messaging = getMessaging(firebaseApp)
const envIsDev = process.env.NODE_ENV === 'development'
const vapidKey = undefined // vapidKey is required
export default function Firebase({ children }) {
return (
<FirebaseProvider
firebaseConfig={firebaseConfig}
firebaseApp={firebaseApp}
envIsDev={envIsDev}
messaging={messaging}
messagingOptions={{
vapidKey,
}}
>
{children}
</FirebaseProvider>
)
}
firebaseConfig = undefined
의 src/services/Firebase/Firebase.tsx
를 Firebase 구성으로 바꿉니다. Firebase 콘솔의 Project settings
에서 찾습니다. vapidKey
Web Push certificates
탭에서 Generate key pair
버튼을 클릭합니다. vapidKey = undefined
의 src/services/Firebase/Firebase.tsx
를 생성된 vapidKey
Firebase.tsx
src/index.tsx
import React from 'react'
import ReactDOM from 'react-dom'
import Firebase from './services/firebase/firebase'
import Router from './pages/router'
import Theme from './theme/theme'
function App() {
return (
<Firebase>
<Theme>
<Router />
</Theme>
</Firebase>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
@useweb/use-firebase-messaging
를 사용하여 FCM 등록 토큰을 검색하고 앱이 포그라운드에 있는 동안 알림을 처리합니다. pages/HomePage/HomePage.tsx
에 다음 코드를 추가합니다.import React, { useEffect } from 'react'
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
import LinearProgress from '@mui/material/LinearProgress'
import useFirebaseMessaging from '@useweb/use-firebase-messaging'
import CopyToClipboard from '../../lib/components/CopyToClipboard/CopyToClipboard'
import Text from '../../lib/components/Text/Text'
import Header from '../../lib/components/_unique/Header/Header'
import useSnackbar from '../../lib/components/Snackbar/Snackbar'
export default function HomePage() {
const snackbar = useSnackbar()
const firebaseMessaging = useFirebaseMessaging({
onMessage: (message) => {
console.log(`Received foreground message`, message)
snackbar.show({
message: message?.notification?.title || message?.data?.title,
})
},
})
useEffect(() => {
firebaseMessaging.init()
}, [])
return (
<Box>
<Header
title='Firebase Messaging Push Notification Example'
tutorialLink='how-to-send-push-notifications-with-firebase-and-react'
repoLink='https://github.com/jeremytenjo/how-to-send-push-notifications-with-firebase-and-react'
/>
{firebaseMessaging.initializing && (
<>
<Text
text='Initializing Firebase Messaging (enable notifications for this page)'
sx={{ mb: 2 }}
/>
<LinearProgress />
</>
)}
{firebaseMessaging.error && (
<Text text={firebaseMessaging.error.toString()} sx={{ color: 'red' }} />
)}
{firebaseMessaging.fcmRegistrationToken && (
<>
<Box
sx={{
display: 'grid',
gridAutoFlow: 'column',
justifyContent: 'start',
alignItems: 'center',
mb: 1,
gridGap: '10px',
}}
>
<Text text='FCM Registration Token:' />
<CopyToClipboard text={firebaseMessaging.fcmRegistrationToken}>
<Button>Copy</Button>
</CopyToClipboard>
</Box>
<Text
text={firebaseMessaging.fcmRegistrationToken}
sx={{
width: '100%',
overflowWrap: 'break-word',
fontSize: '14px',
color: 'grey.main',
}}
/>
</>
)}
</Box>
)
}
이제 생성된 FCM 등록 토큰을 사용하여 푸시 알림을 테스트할 수 있습니다.
http://localhost:3001/
New campaign
버튼을 클릭하십시오 Notifications
버튼을 클릭하십시오 Notification title
및 Notification text
Send test message
http://localhost:3001/
에서 생성된 등록 토큰을 추가하고 더하기 아이콘Test
🎉 앱이 포그라운드에 있으면 앱에 스낵바가 표시되고 앱이 백그라운드에 있으면 기본 알림이 표시됩니다.
클라우드 기능에서 알림 보내기(고급)
FCM registration token
가져오기.const messaging = useFirebaseMessaging({
onFcmRegistrationToken: (fcmRegistrationToken) => {
console.log(fcmRegistrationToken)
},
})
const message = {
data: {
title: `New episodes aired recently!`,
image: `/images/logo/assets/logo.png`,
icon: `/images/logo/assets/logo.png`,
body,
actions: JSON.stringify(actions),
},
tokens: fcmRegistrationToken,
}
functions.logger.info('FCM Message', message)
// https://firebase.google.com/docs/cloud-messaging/send-message#send-messages-to-multiple-devices
const response = await messaging.sendMulticast(message)
지금은 여기까지입니다. 이 튜토리얼이 도움이 되었기를 바랍니다! 아래에 피드백이나 질문을 자유롭게 남겨주세요. 듣고 작업하고 싶습니다.
✌️에서 더 많은 콘텐츠를 확인하려면 팔로우하세요.
Reference
이 문제에 관하여(Firebase 및 React로 푸시 알림을 보내는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/jeremytenjo/how-to-send-push-notifications-with-firebase-and-react-1pol텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)