일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- ts 프로젝트 설정 추천
- ts.config.json default setting
- Blob 사용하는 이유
- 타입스크립트 필수 설정
- ts 설정값
- 인터페이스 vs 타입
- ts.config.json
- TypeScript
- 공부
- Typescript Study
- Blob 청크
- JS Blob
- ts 기초 설정
- 이미지 서버에 업로드
- Null vs Undefined
- TypeScript config
- 인터페이스 타입 비교
- why use interface?
- Blob이란?
- ts 설정
- TypeScript Deep Dive
- JS 이미지 미리보기
- Typescript Handbook
- firebase server
- Interface vs Type Alias
- 프론트 이미지 업로드
- 타입스크립트 설정값
- Blob?
- TypeScript Undefined Null
- ts 필수 설정
- Today
- Total
RPG처럼 웹 개발하기
PWA 푸시알림 어떻게 구현하지? 본문
웹에서 푸시 알림을 보내야하는데 어떻게 보내는지 모르시겠나요?
PWA 로 푸시 알림을 넣고 싶은데 대체 어떻게 하라는건지 하나도 모르시겠나요?
저도 하나도 몰랐지만 아래의 방법으로 기본적인 푸쉬 알림을 띄웠습니다!
제가 만들어본 푸쉬 알림 코드와 사용 방법을 최대한 간단히 적어보겠습니다!
PWA 프로젝트를 진행할때는 처음부터 템플릿을 사용해서 프로젝트를 여는것이 편하고 좋습니다!
npx create-react-app <project-name> --template cra-template-pwa
먼저 index.js 파일에서 serviceWorkerRegistration.register(); 를 실행해줍니다.
serviceWorkerRegistration.unregister(); → serviceWorkerRegistration.register();
이후 serviceWorkerRegistration.js 파일에서
contentType 을 콘솔로 찍어서 javascript 가 나오는지 확인합니다.
여기서!! 위에 contentType 값이 만약 text/html 값이 나온다면
npm run start 로 시작하면 안됩니다.
npm run build → npx serve -s build
위 단계로 실행해주어야 합니다.
( 여기서 아주 많은 삽질을… )
그리고 firebase 프로젝트 만들어줍니다.
프로젝트 설정 부분의 SDK 설정 및 구성을 확인합니다. ( 캡쳐한 사진 아래에 설정 값들이 들어가 있습니다. )
다시 프로젝트로 들어와서
npm install firebase
firebase 모듈을 다운받아줍니다.
public 폴더 경로에 firebase-messaging-sw.js 파일을 생성합니다..
import { initializeApp } from ‘firebase/app’ 이렇게 넣으면 에러나서
importScripts() 형태로 넣습니다.
// public/firebase-messaging-sw.js 파일입니다
importScripts('<https://www.gstatic.com/firebasejs/9.0.0/firebase-app-compat.js>');
importScripts('<https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-compat.js>');
const firebaseConfig = {
apiKey: "firebase 에 있는 키",
authDomain: "window-pwa-test.firebaseapp.com",
projectId: "window-pwa-test",
storageBucket: "window-pwa-test.appspot.com",
messagingSenderId: "firebase에 있는 아이디",
appId: "firebase 에 있는 아이디",
measurementId: "firebase 에 있는 아이디"
};
// firebase 시팅
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
//백그라운드 서비스워커 설정
messaging.onBackgroundMessage(messaging, (payload) => {
console.log("[firebase - messaging - sw.js] Received background message",
payload
);
// 푸시알람 설정
const notificationTitle = "Background Message";
const notificationOptions = {
body: payload,
// icon: "icon.png",
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
그러고 나서,
src 폴더 경로에 fcm.js 파일을 생성합니다.
import { initializeApp } from "firebase/app";
import { getMessaging, getToken, onMessage } from "firebase/messaging";
const firebaseConfig = {
apiKey: "firebase 에 있는 키",
authDomain: "window-pwa-test.firebaseapp.com",
projectId: "window-pwa-test",
storageBucket: "window-pwa-test.appspot.com",
messagingSenderId: "firebase에 있는 아이디",
appId: "firebase 에 있는 아이디",
measurementId: "firebase 에 있는 아이디"
};
const app = initializeApp(firebaseConfig);
// 위에 initializeApp 안해주니까 콘솔에서 에러가 나서 해줬습니다.
const messaging = getMessaging();
//토큰값 얻기
getToken(messaging, {
vapidKey: "웹 푸시 인증서",
})
.then((currentToken) => {
if (currentToken) {
localStorage.setItem('notification-token', currentToken)
console.log(currentToken);
} else {
console.log(
"No registration token available. Request permission to generate one."
);
}
})
.catch((err) => {
console.log("An error occurred while retrieving token.", err);
});
onMessage(messaging, (payload) => {
console.log("Message received.", payload);
});
여기서 로컬 스토리지에 넣어주는 currentToken 이 중요합니다.
사용자를 구분할 수 있는 토큰같은 것입니다.
vapidKey: “웹 푸시 인증서” 구간에는
프로젝트 설정 → 클라우드 메시징 탭에서
웹 구성 → 웹 푸시 인증서에서 받은 키 값을 넣어줍니다.
이렇게 해놓으면 기본적인 푸시 알림을 받기 위한 코드는 넣어놓은 상태입니다.
이제 firebase 에서 알림을 보내거나, POST 요청으로 알림을 보낼 수 있습니다.
푸쉬 알람 보내는 방법
첫번째, POST 요청으로 보내기 ( Postman )
// 요청 주소
**<https://fcm.googleapis.com/fcm/send**>
// json-raw
{
"to": "위에서 클라이언트측에서 받은 currentToken 값",
"notification": {
"title": "test",
"body": "test!"
}
}
// header
{
"Content-Type": "application/json",
"Authorization": "key=서버 키"
}
위에 들어가는 서버 키는 firebase 에서 google cloud 와 연결하면 나옵니다.
위 정보대로 넣어주고 요청을 보내면 푸쉬 알림이 갑니다!
두번째 firebase 에서 알림 보내기
참여 / Colud Messaging ( 없다면 Messaging ) 탭을 클릭해서 들어갑니다.
새로운 캠페인 ( 알림 ) 을 만들어서 내용을 작성하고 테스트 메세지 전송 클릭!
FCM 등록 토큰 추가를 클릭하고, 아까 클라이언트에서 받은 currentToken 을 입력하고 테스트 클릭!
정상적으로 작동한다면 캠페인을 마저 작성합니다.
그러고나면 이제 해당 앱을 다운받고 알림 설정을 허용한 유저들에게 약 5 ~ 10분뒤 쯤 알림이 갑니다.
몇개의 푸쉬 알림이 전송되었으며, 몇개가 오픈되었는지도 확인할 수 있습니다!
'웹 개발' 카테고리의 다른 글
Interface VS Type alias 비교하기 (0) | 2022.11.20 |
---|---|
Blob으로 이미지 업로드 훑어보기 (0) | 2022.10.02 |
시멘틱 태그( Sematic Tag )를 잘 사용하는 방법? (0) | 2022.08.24 |
웹 성능을 최적화하는 쉽고 간단한 방법? ( feat. 이미지 ) (0) | 2022.08.09 |
CSS 함수 clamp를 사용해보았다. (0) | 2022.07.28 |