FCM(Firebase Cloud Messaging)
https://console.firebase.google.com/?pli=1
Firebase 프로젝트 시작하기
프로젝트 이름 생성
동의 후, 프로젝트 만들기
일반 탭 => 하단 내 앱 -> 코드 모양 버튼 클릭
앱 닉네임 설정 후, 앱 생성 클릭하면
SDK 코드 생성
호스팅 설정, 콘솔로 이동
// /public/firebase-messaging-sw.js
importScripts("https://www.gstatic.com/firebasejs/9.14.0/firebase-app-compat.js");
importScripts("https://www.gstatic.com/firebasejs/9.14.0/firebase-messaging-compat.js");
// FIRE-BASE 앱 등록할때 받은 'firebaseConfig' 값을 넣어주세요.
const config = {
apiKey: "apiKey값",
authDomain: "authDomain값",
projectId: "projectId",
storageBucket: "storageBucket",
messagingSenderId: "messagingSenderId",
appId: "appId",
measurementId: "measurementId",
};
// Initialize Firebase
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.onBackgroundMessage((payload) => {
console.log("[firebase-messaging-sw.js] Received background message ", payload);
const { title, body, image, click_action } = payload.data;
self.registration.showNotification(title, { body, image, click_action });
});
self.addEventListener("push", function (event) {
if (event.data) {
// 알림 메세지일 경우엔 event.data.json().notification;
const { title, body, image, click_action } = event.data.json().data;
event.waitUntil(self.registration.showNotification(title, { body, image, data: { click_action } }));
} else {
console.log("This push event has no data.");
}
});
// 클릭 이벤트 처리
self.addEventListener("notificationclick", function (event) {
event.preventDefault();
// 알림창 닫기
event.notification.close();
// 이동할 url
const urlToOpen = event.notification.data.click_action;
// 사이트 열려있는지 체크
const promiseChain = clients
.matchAll({
type: "window",
includeUncontrolled: true,
})
.then(function (windowClients) {
let matchingClient = null;
for (let i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
if (windowClient.url.includes(urlToOpen)) {
matchingClient = windowClient;
break;
}
}
if (matchingClient) {
return matchingClient.focus();
} else {
return clients.openWindow(urlToOpen);
}
});
event.waitUntil(promiseChain);
});