React-Query ← 이론 공부할 때 괜찮습니다.

FCM Front 해줘야 하는것

  1. 서비스 워커 설정

    무조건 public 폴더에 firebase-messaging-sw.js 이름으로 만들어야 합니다.

    백그라운드 메세지는 service worker에서만 컨트롤할 수 있습니다.

    Untitled

    importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js');
    importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js');
    
    firebase.initializeApp({
        apiKey: "AIzaSyBih65GoaQRf_RbFYM3XYNDb0WjJQj6xhc",
        authDomain: "whoru-29e56.firebaseapp.com",
        projectId: "whoru-29e56",
        storageBucket: "whoru-29e56.appspot.com",
        messagingSenderId: "1051109766348",
        appId: "1:1051109766348:web:dbc586010d56e55b0bfe69",
        measurementId: "G-16THNFKQN9"
    });
    
    const messaging = firebase.messaging();
    
    messaging.onBackgroundMessage((payload) => {
        // 백그라운드 메세지 핸들러, 백그라운드 메세지는 Service-worker에서만 작동함!    
        const notificationTitle = 'Background Message Title'; // 메세지 제목
        const notificationOptions = {
            body: payload.body, // 매세지 내용
            icon: '/firebase-logo.png' // 로고 이미지 들어가는곳
        };
        self.registration.showNotification(notificationTitle, notificationOptions);
    });
    
  2. FirebaseUtil.js 는 src에 알맞은 경로에 넣어두시면 됩니다.

    import { initializeApp } from "firebase/app";
    import { getToken, getMessaging } from "firebase/messaging";
    
    const firebaseConfig = {
      apiKey: "AIzaSyBih65GoaQRf_RbFYM3XYNDb0WjJQj6xhc",
      authDomain: "whoru-29e56.firebaseapp.com",
      projectId: "whoru-29e56",
      storageBucket: "whoru-29e56.appspot.com",
      messagingSenderId: "1051109766348",
      appId: "1:1051109766348:web:dbc586010d56e55b0bfe69",
      measurementId: "G-16THNFKQN9"
    };
    
    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const messaging = getMessaging(app);
    
    async function requestPermission(){
        const permission = await Notification.requestPermission();
        if(permission === "denied"){
            console.log("알림받기가 꺼져있습니다.")
            return;
        }
    
        const token = await getToken(messaging, {
            vapidKey: "BOJrA8KgnUI2pEEzLEfsVNjlEPB9vmvh_0Km-lsp714IRV9cgwgc5mi3ynx5uCBHzhbiPeMJ8v9_EH9oP_x_Emc"
        })
    
        if(token) console.log("token: ",token)  
        // 토큰 잘 받아오는지 체크하는 console 나중에 꼭 지울것!!
        return token
    }
    
    function getFirebaseMessagingObject(){
        return messaging
    }
    
    export { requestPermission, getFirebaseMessagingObject } 
    
  3. 기본 FCM 컴포넌트 사용예시

// App.js
import logo from './logo.svg';
import './App.css';
import { requestPermission } from './FirebaseUtil'
import { useEffect, useState } from 'react';
import { FCMComponent } from './FCM';

function App() {
  const [token, setToken] = useState("")
  useEffect(()=>{
    const resultToken = requestPermission()
    resultToken.then((token)=>{
      setToken(token)
    })
  }, [])
  return (
    <div className="App">
      <header className="App-header">
        <h1>FCM 놀이터</h1>
        <FCMComponent token={token}/>
      </header>
    </div>
  );
}

export default App;

// FCM.jsx
import { useEffect, useRef, useState } from "react"
import { getFirebaseMessagingObject } from "./FirebaseUtil"
import { onMessage } from "firebase/messaging";

export const FCMComponent = (props) => {
    const [text, setText] = useState("");
    const messagingObject = useRef(null);
    useEffect(()=>{
        messagingObject.current = getFirebaseMessagingObject()
    },[])
    if(messagingObject.current !== null){
        onMessage(messagingObject.current, (body)=>{
            alert(body.notification.body)
        })
    }
    const onChangeHandler = (e) =>{
        setText(e.target.value);
    }
    const onClickHandler = (e) =>{
    // 여기부분은 axios가 편하시면 바꿔서 사용하시면 됨
        fetch("나중에 올라갈 서버 주소",{
            method: "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                token: props.token,
                content: text
            })
        })
    }
    return (
        <div>
            <input type="text" value={text} onChange={onChangeHandler}/>
            <button onClick={onClickHandler}> 메세지 발송 </button>
        </div>
    )
}