
개요
이전 포스트에서 작성하였던 것과 같이 notification과 data가 함께 있는 Push 메시지를 수신할 경우 앱이 Background 상태일 때, SDK 만 사용할 경우 data 부분이 앱으로 전달되지 않는 문제가 있었습니다.
웹앱(PWA)이 백그라운드 상태일 때, 푸시 메시지에 포함된 data 페이로드가 앱으로 전달되어도 처리할 수 있는 핸들러를 SDK에서 제공하지 않았습니다. 이전 포스트에서는 push 이벤트 핸들러를 등록하여 임의로 해결하였으나 SDK의 버전이 갱신되며 이 부분을 SDK 상에서 수정해주어 사용법을 소개합니다.
notification + data 메시지 수신하기
Firebase JavaScript SDK 7.18.0 버전을 출시하며 Firebase Cloud Messaging 부분의 기능이 수정되었습니다. 푸시 알림이 표시된 후에도 호출되는 onBackgroundMessage()가 제공됩니다.
사용법은 간단한데 호출하는 SDK를 7.18.0 으로 교체한 후, setBackgroundMessageHandler를 onBackgroundMessage로 변경합니다.
importScripts("/__/firebase/7.18.0/firebase-app.js");
importScripts("/__/firebase/7.18.0/firebase-messaging.js");
importScripts("/__/firebase/init.js");
const messaging = firebase.messaging();
// If you would like to customize notifications that are received in the
// background (Web app is closed or not in browser focus) then you should
// implement this optional method.
// [START background_handler]
messaging.onBackgroundMessage(payload => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
const { title, ...options } = payload.data;
return self.registration.showNotification(
title,
options
);
});
▲ firebase-messaging-sw.js
수정한 코드를 이용하여 푸시 메시지를 수신해보면, 다음 그림과 같이 웹앱(PWA)이 활성화되어 있는 경우는 이전과 같이 onMessage()에서 수신하며, 주요 관심사인 웹앱(PWA)이 비활성화(Background) 상태인 경우에 data 페이로드가 포함되어 있더라도 onBackgroundMessage()가 호출되며, 전송한 notification 페이로드 및 data 페이로드가 해당 핸들러로 전달된 것을 확인할 수 있습니다.

참고
'모듈, 프레임웍 > Firebase' 카테고리의 다른 글
| [Firebase] Cloud Function Node.js 런타임 업그레이드 (0) | 2021.01.27 |
|---|---|
| [Firebase] Cloud Firestore Collection에 포함된 Doc 갯수 세기 (0) | 2021.01.06 |
| Firebase Cloud Messaging - 푸시 메시지 유형 및 수신 (0) | 2020.08.11 |
| Firebase Cloud Messaging - 클라이언트(JavaScript) 설정 (0) | 2020.07.28 |
| Firebase 호스팅 사용하기 - Custom Domain 연결 (0) | 2020.07.21 |