-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfirebase-messaging-sw.ts
62 lines (51 loc) · 1.78 KB
/
firebase-messaging-sw.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { initializeApp } from 'firebase/app';
import { getMessaging, getToken, onMessage } from 'firebase/messaging';
import { endPoint } from 'constants/endPoint';
import { tokenAxios } from 'utils/axios';
const firebaseConfig = {
apiKey: import.meta.env.VITE_API_KEY,
authDomain: 'allreva-86be8.firebaseapp.com',
projectId: 'allreva-86be8',
storageBucket: 'allreva-86be8.firebasestorage.app',
messagingSenderId: import.meta.env.VITE_MESSAGING_SENDER_ID,
appId: import.meta.env.VITE_APP_ID,
measurementId: import.meta.env.VITE_MEASUREMENT_ID,
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/firebase-messaging-sw.js')
.then((registration) => {
console.log('Service Worker registered with scope:', registration.scope);
})
.catch((err) => {
console.error('Service Worker registration failed:', err);
});
}
export async function requestPermission() {
console.log('권한 요청 중...');
const permission = await Notification.requestPermission();
if (permission === 'denied') {
console.log('알림 권한이 허용되지 않았습니다');
return;
}
console.log('알림 권한이 허용되었습니다');
const token = await getToken(messaging, {
vapidKey: import.meta.env.VITE_VAPID_KEY,
});
if (token) {
console.log('token: ', token);
try {
await tokenAxios.post(endPoint.GET_NOTIFICATION_TOKEN, { deviceToken: token });
} catch (error) {
console.error('토큰 전송에 실패했습니다', error);
}
} else {
console.log('token을 얻을 수 없습니다');
}
onMessage(messaging, (payload) => {
console.log('메시지가 도착했습니다.', payload);
});
}