Feat: firebase 구현 중

This commit is contained in:
홍창기 2024-09-25 18:59:54 +09:00
parent f78d4ac7fb
commit 224f8f2b37
2 changed files with 63 additions and 97 deletions

View File

@ -1,57 +1,13 @@
// import { initializeApp } from 'firebase/app';
// import { getMessaging, getToken } from 'firebase/messaging';
import { initializeApp } from 'firebase/app';
// 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,
// };
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,
};
// export const app = initializeApp(firebaseConfig);
// export const messaging = getMessaging(app);
// export async function registerServiceWorker() {
// if ('serviceWorker' in navigator) {
// try {
// console.log('서비스 워커 등록 시도 중...');
// const firebaseRegistration = await navigator.serviceWorker.register('/firebase-messaging-sw.js');
// console.log('Firebase Service Worker 등록 성공');
// console.log('서비스 워커 활성화 대기 중...');
// const serviceWorker = await navigator.serviceWorker.ready;
// console.log('서비스 워커 활성화');
// if (serviceWorker && !sessionStorage.getItem('fcmToken')) {
// console.log('세션 체크 중...');
// const permission = await Notification.requestPermission();
// if (permission === 'granted') {
// console.log('알림 권한 허용됨');
// const currentToken = await getToken(messaging, {
// vapidKey: 'BApIruZrx83suCd09dnDCkFSP_Ts08q38trrIL6GHpChtbjQHTHk_38_JRyTiKLqciHxLQ8iXtie3lvgyb4Iphg',
// serviceWorkerRegistration: firebaseRegistration,
// });
// if (currentToken) {
// sessionStorage.setItem('fcmToken', currentToken);
// } else {
// console.warn('FCM 토큰을 가져올 수 없습니다. 권한이 없거나 문제가 발생했습니다.');
// }
// } else {
// console.log('알림 권한이 거부되었습니다.');
// }
// }
// } catch (error) {
// console.error('Service Worker 등록 실패:', error);
// }
// } else {
// console.warn('Service Worker not supported in this browser');
// }
// }
export const firebaseApp = initializeApp(firebaseConfig);

View File

@ -1,76 +1,86 @@
import { createTestNotification, saveFcmToken } from '@/api/authApi';
import { Button } from '@/components/ui/button';
import { initializeApp } from 'firebase/app';
import { firebaseApp } from '@/firebase';
import { getMessaging, getToken, onMessage } from 'firebase/messaging';
import { useEffect } from 'react';
export default function FirebaseTest() {
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,
};
useEffect(() => {
const messaging = getMessaging(firebaseApp);
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
onMessage(messaging, (payload) => {
console.log('Message recieved. ', payload);
onMessage(messaging, (payload) => {
console.log('Message recieved. ', payload);
if (!payload || !payload.notification) return;
if (!payload || !payload.notification) return;
const { title, body } = payload.notification;
// 메시지 내용에 따라 사용자에게 알림을 표시할 수 있습니다.
const { title, body } = payload.notification;
if (!title || !body) return;
if (!title || !body) return;
new Notification(title, { body });
});
new Notification(title, { body });
});
}, []);
const getFcmToken = async () => {
const permission = await Notification.requestPermission();
const existingToken = sessionStorage.getItem('fcmToken');
if (permission === 'granted') {
const currentToken = await getToken(messaging, {
vapidKey: 'BApIruZrx83suCd09dnDCkFSP_Ts08q38trrIL6GHpChtbjQHTHk_38_JRyTiKLqciHxLQ8iXtie3lvgyb4Iphg',
});
if (currentToken) {
sessionStorage.setItem('fcmToken', currentToken);
console.log(currentToken);
} else {
console.warn('FCM 토큰을 가져올 수 없습니다. 권한이 없거나 문제가 발생했습니다.');
}
} else {
console.log('알림 권한이 거부되었습니다.');
if (existingToken) {
console.log(existingToken);
return existingToken;
}
return null;
try {
const permission = await Notification.requestPermission();
if (permission === 'granted') {
const messaging = getMessaging(firebaseApp);
const currentToken = await getToken(messaging, {
vapidKey: 'BApIruZrx83suCd09dnDCkFSP_Ts08q38trrIL6GHpChtbjQHTHk_38_JRyTiKLqciHxLQ8iXtie3lvgyb4Iphg',
});
if (currentToken) {
console.log(currentToken);
sessionStorage.setItem('fcmToken', currentToken);
return currentToken;
}
console.warn('FCM 토큰을 가져올 수 없습니다. 권한이 없거나 문제가 발생했습니다.');
return null;
}
console.log('알림 권한이 거부되었습니다.');
return null;
} catch (error) {
console.error('FCM 토큰을 가져오는 중 오류가 발생했습니다.');
return null;
}
};
const handleSaveToken = () => {
const fcmToken = sessionStorage.getItem('fcmToken');
console.log(fcmToken);
if (fcmToken) {
saveFcmToken(fcmToken);
console.log(fcmToken);
}
};
const handleTest = () => {
const handleTestNotification = () => {
createTestNotification();
console.log('ok');
};
getFcmToken();
return (
<div>
<h1 className="heading p-2">hello, firebase!</h1>
<div className="p-2">
<Button
onClick={getFcmToken}
variant="outlinePrimary"
className="mr-2"
>
getFcmToken
</Button>
<Button
onClick={handleSaveToken}
variant="outlinePrimary"
@ -79,10 +89,10 @@ export default function FirebaseTest() {
handleSaveToken
</Button>
<Button
onClick={handleTest}
onClick={handleTestNotification}
variant="outlinePrimary"
>
handleTest
handleTestNotification
</Button>
</div>
</div>