From f38b0512f11fb616b8dae70d0e47efddcb9e14c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=ED=99=8D=EC=B0=BD=EA=B8=B0?= Date: Fri, 27 Sep 2024 09:01:03 +0900 Subject: [PATCH] =?UTF-8?q?Feat:=20FCM=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/public/firebase-messaging-sw.js | 14 ++- frontend/public/serviceWorkerRegistration.js | 89 +++++++++++--------- frontend/src/api/firebaseConfig.ts | 32 +++---- frontend/src/pages/FirebaseTest.tsx | 18 ++-- 4 files changed, 81 insertions(+), 72 deletions(-) diff --git a/frontend/public/firebase-messaging-sw.js b/frontend/public/firebase-messaging-sw.js index 92bf787..47c2b15 100644 --- a/frontend/public/firebase-messaging-sw.js +++ b/frontend/public/firebase-messaging-sw.js @@ -3,16 +3,24 @@ importScripts('https://www.gstatic.com/firebasejs/8.7.1/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/8.7.1/firebase-messaging.js'); +const firebaseConfig = { + apiKey: 'AIzaSyBQx50AsrS3K687cGbFDh1908ClCLFmnhA', + authDomain: 'worlabel-6de69.firebaseapp.com', + projectId: 'worlabel-6de69', + storageBucket: 'worlabel-6de69.appspot.com', + messagingSenderId: '124097400880', + appId: '1:124097400880:web:022db3cdc0bdea750c5df5', + measurementId: 'G-KW02YRYF5H', +}; + self.addEventListener('install', (_) => { self.skipWaiting(); }); self.addEventListener('activate', (_) => { - console.log('FCM service worker가 실행되었습니다.'); + console.log('FCM 서비스 워커가 실행되었습니다.'); }); -const firebaseConfig = {}; - firebase.initializeApp(firebaseConfig); const messaging = firebase.messaging(); diff --git a/frontend/public/serviceWorkerRegistration.js b/frontend/public/serviceWorkerRegistration.js index c939962..d5fd0c6 100644 --- a/frontend/public/serviceWorkerRegistration.js +++ b/frontend/public/serviceWorkerRegistration.js @@ -1,56 +1,61 @@ +/* eslint-disable no-undef */ import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js'; import { getMessaging, getToken } from 'https://www.gstatic.com/firebasejs/9.1.3/firebase-messaging.js'; -const firebaseConfig = {}; +const firebaseConfig = { + apiKey: 'AIzaSyBQx50AsrS3K687cGbFDh1908ClCLFmnhA', + authDomain: 'worlabel-6de69.firebaseapp.com', + projectId: 'worlabel-6de69', + storageBucket: 'worlabel-6de69.appspot.com', + messagingSenderId: '124097400880', + appId: '1:124097400880:web:022db3cdc0bdea750c5df5', + measurementId: 'G-KW02YRYF5H', +}; const firebaseApp = initializeApp(firebaseConfig); const messaging = getMessaging(firebaseApp); const registerServiceWorker = async () => { - if ('serviceWorker' in navigator) { - try { - console.log('Service Worker 등록 중...'); - const firebaseRegistration = await navigator.serviceWorker.register('/firebase-messaging-sw.js'); - console.log('Service Worker 등록 성공'); - - console.log('Service Worker 활성화 중...'); - const serviceWorker = await navigator.serviceWorker.ready; - console.log('Service Worker 활성화 성공'); - - if (serviceWorker && !sessionStorage.getItem('fcmToken')) { - const permission = await Notification.requestPermission(); - - if (permission === 'granted') { - console.log('알림 권한이 허용되었습니다.'); - - try { - console.log('FCM 토큰 발급 중...'); - const currentToken = await getToken(messaging, { - vapidKey: 'BApIruZrx83suCd09dnDCkFSP_Ts08q38trrIL6GHpChtbjQHTHk_38_JRyTiKLqciHxLQ8iXtie3lvgyb4Iphg', - serviceWorkerRegistration: firebaseRegistration, - }); - console.log('FCM 토큰 발급 성공'); - - if (currentToken) { - sessionStorage.setItem('fcmToken', currentToken); - } - } catch (error) { - console.warn('FCM 토큰을 가져올 수 없습니다.'); - } - - return; - } - - console.log('알림 권한이 거부되었습니다.'); - } - } catch (error) { - console.error('Service Worker 등록에 실패했습니다. : ', error); - } - + if (!('serviceWorker' in navigator)) { + console.warn('현재 브라우저에서 Service Worker를 지원하지 않습니다.'); return; } - console.warn('현재 브라우저에서 Service Worker를 지원하지 않습니다.'); + try { + console.log('FCM 서비스 워커 등록 중...'); + const firebaseRegistration = await navigator.serviceWorker.register('/firebase-messaging-sw.js'); + console.log('FCM 서비스 워커 등록 성공'); + + console.log('FCM 서비스 워커 활성화 중...'); + const serviceWorker = await navigator.serviceWorker.ready; + console.log('FCM 서비스 워커 활성화 성공'); + + if (serviceWorker && !sessionStorage.getItem('fcmToken')) { + const permission = await Notification.requestPermission(); + + if (permission === 'granted') { + console.log('알림 권한이 허용되었습니다.'); + + console.log('FCM 토큰 발급 중...'); + const currentToken = await getToken(messaging, { + vapidKey: 'BApIruZrx83suCd09dnDCkFSP_Ts08q38trrIL6GHpChtbjQHTHk_38_JRyTiKLqciHxLQ8iXtie3lvgyb4Iphg', + serviceWorkerRegistration: firebaseRegistration, + }); + console.log('FCM 토큰 발급 성공'); + + if (currentToken) { + sessionStorage.setItem('fcmToken', currentToken); + } else { + console.warn('FCM 토큰을 가져올 수 없습니다.'); + } + } else { + console.log('알림 권한이 거부되었습니다.'); + } + } + } catch (error) { + console.error('FCM 서비스 워커 등록에 실패했습니다. : ', error); + } }; +// 서비스 워커 등록 함수 호출 registerServiceWorker(); diff --git a/frontend/src/api/firebaseConfig.ts b/frontend/src/api/firebaseConfig.ts index f1e0fa8..59d7628 100644 --- a/frontend/src/api/firebaseConfig.ts +++ b/frontend/src/api/firebaseConfig.ts @@ -2,13 +2,13 @@ import { initializeApp } from 'firebase/app'; import { getMessaging, getToken, onMessage } from 'firebase/messaging'; const firebaseConfig = { - apiKey: import.meta.env.VITE_FIREBASE_API_KEY, - authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN, - projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID, - storageBucket: import.meta.env.VITE_FIREBASE_STORAGE_BUCKET, - messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID, - appId: import.meta.env.VITE_FIREBASE_APP_ID, - measurementId: import.meta.env.VITE_FIREBASE_MEASUREMENT_ID, + apiKey: String(import.meta.env.VITE_FIREBASE_API_KEY), + authDomain: String(import.meta.env.VITE_FIREBASE_AUTH_DOMAIN), + projectId: String(import.meta.env.VITE_FIREBASE_PROJECT_ID), + storageBucket: String(import.meta.env.VITE_FIREBASE_STORAGE_BUCKET), + messagingSenderId: String(import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID), + appId: String(import.meta.env.VITE_FIREBASE_APP_ID), + measurementId: String(import.meta.env.VITE_FIREBASE_MEASUREMENT_ID), }; const firebaseApp = initializeApp(firebaseConfig); @@ -18,16 +18,21 @@ const getFcmToken = async () => { const existingToken = sessionStorage.getItem('fcmToken'); if (existingToken) { - return existingToken; // 이미 토큰이 있는 경우, 해당 토큰을 반환한다. + // 이미 토큰이 있는 경우, 해당 토큰을 반환한다. + return existingToken; } try { const permission = await Notification.requestPermission(); if (permission === 'granted') { + console.log('알림 권한이 허용되었습니다.'); + + console.log('FCM 토큰 발급 중...'); const currentToken = await getToken(messaging, { - vapidKey: 'BGVbiPhLWWxijrc2jfn9lTyDs-kcSfSinb2bUmEoDXSc8ljx6sWtur9k82vmjBLND06SSeb10oq-rw7zmzrpoPY', + vapidKey: 'BApIruZrx83suCd09dnDCkFSP_Ts08q38trrIL6GHpChtbjQHTHk_38_JRyTiKLqciHxLQ8iXtie3lvgyb4Iphg', }); + console.log('FCM 토큰 발급 성공'); if (currentToken) { sessionStorage.setItem('fcmToken', currentToken); @@ -35,14 +40,11 @@ const getFcmToken = async () => { } console.warn('FCM 토큰을 가져올 수 없습니다.'); - return null; + } else { + console.log('알림 권한이 거부되었습니다.'); } - - console.log('알림 권한이 거부되었습니다.'); - return null; } catch (error) { - console.error('FCM 토큰을 가져오는 중 오류가 발생했습니다 : ', error); - return null; + console.error('FCM 토큰을 가져오는 중 오류가 발생했습니다. : ', error); } }; diff --git a/frontend/src/pages/FirebaseTest.tsx b/frontend/src/pages/FirebaseTest.tsx index b142036..906ef2e 100644 --- a/frontend/src/pages/FirebaseTest.tsx +++ b/frontend/src/pages/FirebaseTest.tsx @@ -7,22 +7,16 @@ export default function FirebaseTest() { const fcmToken = await getFcmToken(); if (fcmToken) { - await saveFcmToken(fcmToken); console.log(fcmToken); + await saveFcmToken(fcmToken); return; } - console.log('저장된 FCM token이 없습니다.'); + console.log('FCM 토큰이 없습니다.'); }; - const handleTestNotification = async () => { - await createFcmNotification() - .then(() => { - console.log('테스트 알림에 성공했습니다.'); - }) - .catch(() => { - console.log('테스트 알림에 실패했습니다.'); - }); + const handleCreateNotification = async () => { + await createFcmNotification(); }; handleForegroundMessages(); @@ -36,10 +30,10 @@ export default function FirebaseTest() { variant="outlinePrimary" className="mr-2" > - FCM 토큰 불러와서 redis에 저장 + FCM 토큰 서버에 저장