Feat: FCM 구현

This commit is contained in:
홍창기 2024-09-27 09:01:03 +09:00
parent de723381b3
commit f38b0512f1
No known key found for this signature in database
GPG Key ID: 9FF142041B4A91B9
4 changed files with 81 additions and 72 deletions

View File

@ -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-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.7.1/firebase-messaging.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.addEventListener('install', (_) => {
self.skipWaiting(); self.skipWaiting();
}); });
self.addEventListener('activate', (_) => { self.addEventListener('activate', (_) => {
console.log('FCM service worker가 실행되었습니다.'); console.log('FCM 서비스 워커가 실행되었습니다.');
}); });
const firebaseConfig = {};
firebase.initializeApp(firebaseConfig); firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging(); const messaging = firebase.messaging();

View File

@ -1,21 +1,34 @@
/* eslint-disable no-undef */
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js'; 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'; 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 firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp); const messaging = getMessaging(firebaseApp);
const registerServiceWorker = async () => { const registerServiceWorker = async () => {
if ('serviceWorker' in navigator) { if (!('serviceWorker' in navigator)) {
try { console.warn('현재 브라우저에서 Service Worker를 지원하지 않습니다.');
console.log('Service Worker 등록 중...'); return;
const firebaseRegistration = await navigator.serviceWorker.register('/firebase-messaging-sw.js'); }
console.log('Service Worker 등록 성공');
console.log('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; const serviceWorker = await navigator.serviceWorker.ready;
console.log('Service Worker 활성화 성공'); console.log('FCM 서비스 워커 활성화 성공');
if (serviceWorker && !sessionStorage.getItem('fcmToken')) { if (serviceWorker && !sessionStorage.getItem('fcmToken')) {
const permission = await Notification.requestPermission(); const permission = await Notification.requestPermission();
@ -23,7 +36,6 @@ const registerServiceWorker = async () => {
if (permission === 'granted') { if (permission === 'granted') {
console.log('알림 권한이 허용되었습니다.'); console.log('알림 권한이 허용되었습니다.');
try {
console.log('FCM 토큰 발급 중...'); console.log('FCM 토큰 발급 중...');
const currentToken = await getToken(messaging, { const currentToken = await getToken(messaging, {
vapidKey: 'BApIruZrx83suCd09dnDCkFSP_Ts08q38trrIL6GHpChtbjQHTHk_38_JRyTiKLqciHxLQ8iXtie3lvgyb4Iphg', vapidKey: 'BApIruZrx83suCd09dnDCkFSP_Ts08q38trrIL6GHpChtbjQHTHk_38_JRyTiKLqciHxLQ8iXtie3lvgyb4Iphg',
@ -33,24 +45,17 @@ const registerServiceWorker = async () => {
if (currentToken) { if (currentToken) {
sessionStorage.setItem('fcmToken', currentToken); sessionStorage.setItem('fcmToken', currentToken);
} } else {
} catch (error) {
console.warn('FCM 토큰을 가져올 수 없습니다.'); console.warn('FCM 토큰을 가져올 수 없습니다.');
} }
} else {
return;
}
console.log('알림 권한이 거부되었습니다.'); console.log('알림 권한이 거부되었습니다.');
} }
}
} catch (error) { } catch (error) {
console.error('Service Worker 등록에 실패했습니다. : ', error); console.error('FCM 서비스 워커 등록에 실패했습니다. : ', error);
} }
return;
}
console.warn('현재 브라우저에서 Service Worker를 지원하지 않습니다.');
}; };
// 서비스 워커 등록 함수 호출
registerServiceWorker(); registerServiceWorker();

View File

@ -2,13 +2,13 @@ import { initializeApp } from 'firebase/app';
import { getMessaging, getToken, onMessage } from 'firebase/messaging'; import { getMessaging, getToken, onMessage } from 'firebase/messaging';
const firebaseConfig = { const firebaseConfig = {
apiKey: import.meta.env.VITE_FIREBASE_API_KEY, apiKey: String(import.meta.env.VITE_FIREBASE_API_KEY),
authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN, authDomain: String(import.meta.env.VITE_FIREBASE_AUTH_DOMAIN),
projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID, projectId: String(import.meta.env.VITE_FIREBASE_PROJECT_ID),
storageBucket: import.meta.env.VITE_FIREBASE_STORAGE_BUCKET, storageBucket: String(import.meta.env.VITE_FIREBASE_STORAGE_BUCKET),
messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID, messagingSenderId: String(import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID),
appId: import.meta.env.VITE_FIREBASE_APP_ID, appId: String(import.meta.env.VITE_FIREBASE_APP_ID),
measurementId: import.meta.env.VITE_FIREBASE_MEASUREMENT_ID, measurementId: String(import.meta.env.VITE_FIREBASE_MEASUREMENT_ID),
}; };
const firebaseApp = initializeApp(firebaseConfig); const firebaseApp = initializeApp(firebaseConfig);
@ -18,16 +18,21 @@ const getFcmToken = async () => {
const existingToken = sessionStorage.getItem('fcmToken'); const existingToken = sessionStorage.getItem('fcmToken');
if (existingToken) { if (existingToken) {
return existingToken; // 이미 토큰이 있는 경우, 해당 토큰을 반환한다. // 이미 토큰이 있는 경우, 해당 토큰을 반환한다.
return existingToken;
} }
try { try {
const permission = await Notification.requestPermission(); const permission = await Notification.requestPermission();
if (permission === 'granted') { if (permission === 'granted') {
console.log('알림 권한이 허용되었습니다.');
console.log('FCM 토큰 발급 중...');
const currentToken = await getToken(messaging, { const currentToken = await getToken(messaging, {
vapidKey: 'BGVbiPhLWWxijrc2jfn9lTyDs-kcSfSinb2bUmEoDXSc8ljx6sWtur9k82vmjBLND06SSeb10oq-rw7zmzrpoPY', vapidKey: 'BApIruZrx83suCd09dnDCkFSP_Ts08q38trrIL6GHpChtbjQHTHk_38_JRyTiKLqciHxLQ8iXtie3lvgyb4Iphg',
}); });
console.log('FCM 토큰 발급 성공');
if (currentToken) { if (currentToken) {
sessionStorage.setItem('fcmToken', currentToken); sessionStorage.setItem('fcmToken', currentToken);
@ -35,14 +40,11 @@ const getFcmToken = async () => {
} }
console.warn('FCM 토큰을 가져올 수 없습니다.'); console.warn('FCM 토큰을 가져올 수 없습니다.');
return null; } else {
}
console.log('알림 권한이 거부되었습니다.'); console.log('알림 권한이 거부되었습니다.');
return null; }
} catch (error) { } catch (error) {
console.error('FCM 토큰을 가져오는 중 오류가 발생했습니다 : ', error); console.error('FCM 토큰을 가져오는 중 오류가 발생했습니다. : ', error);
return null;
} }
}; };

View File

@ -7,22 +7,16 @@ export default function FirebaseTest() {
const fcmToken = await getFcmToken(); const fcmToken = await getFcmToken();
if (fcmToken) { if (fcmToken) {
await saveFcmToken(fcmToken);
console.log(fcmToken); console.log(fcmToken);
await saveFcmToken(fcmToken);
return; return;
} }
console.log('저장된 FCM token이 없습니다.'); console.log('FCM 토큰이 없습니다.');
}; };
const handleTestNotification = async () => { const handleCreateNotification = async () => {
await createFcmNotification() await createFcmNotification();
.then(() => {
console.log('테스트 알림에 성공했습니다.');
})
.catch(() => {
console.log('테스트 알림에 실패했습니다.');
});
}; };
handleForegroundMessages(); handleForegroundMessages();
@ -36,10 +30,10 @@ export default function FirebaseTest() {
variant="outlinePrimary" variant="outlinePrimary"
className="mr-2" className="mr-2"
> >
FCM redis FCM
</Button> </Button>
<Button <Button
onClick={handleTestNotification} onClick={handleCreateNotification}
variant="outlinePrimary" variant="outlinePrimary"
className="mr-2" className="mr-2"
> >