자바스크립트 클라이언트에서 메시지 수신

메시지의 동작은 페이지가 포커스를 갖는 포그라운드 상태인지, 백그라운드 상태인지, 다른 탭 뒤에 숨겨져 있는지, 완전히 닫혀 있는지에 따라 다릅니다. 어떠한 경우든 페이지는 onMessage 콜백을 처리해야 합니다. 하지만 백그라운드 상태인 경우에는 onBackgroundMessage를 처리하거나 사용자가 웹 앱을 포그라운드로 전환할 수 있도록 화면 알림을 구성해야 할 수도 있습니다.

앱 상태 알림 데이터 모두
포그라운드 onMessage onMessage onMessage
백그라운드(서비스 워커) onBackgroundMessage(화면 알림이 자동으로 표시됨) onBackgroundMessage onBackgroundMessage(화면 알림이 자동으로 표시됨)

자바스크립트 빠른 시작 샘플에서는 메시지를 수신하는 데 필요한 모든 코드를 보여줍니다.

웹 앱이 포그라운드 상태일 때 메시지 처리

onMessage 이벤트를 수신하려면 앱에서 firebase-messaging-sw.js에 Firebase 메시징 서비스 워커를 정의해야 합니다. 또는 getToken(): Promise<string>를 통해 SDK에 기존 서비스 워커를 제공할 수 있습니다.

웹 모듈식 API

import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging/sw";

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
const firebaseApp = initializeApp({
  apiKey: 'api-key',
  authDomain: 'project-id.firebaseapp.com',
  databaseURL: 'https://project-id.firebaseio.com',
  projectId: 'project-id',
  storageBucket: 'project-id.appspot.com',
  messagingSenderId: 'sender-id',
  appId: 'app-id',
  measurementId: 'G-measurement-id',
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = getMessaging(firebaseApp);

웹 네임스페이스화된 API

// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here. Other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js');

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp({
  apiKey: 'api-key',
  authDomain: 'project-id.firebaseapp.com',
  databaseURL: 'https://project-id.firebaseio.com',
  projectId: 'project-id',
  storageBucket: 'project-id.appspot.com',
  messagingSenderId: 'sender-id',
  appId: 'app-id',
  measurementId: 'G-measurement-id',
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();

앱이 포그라운드 상태일 때, 즉 사용자가 현재 웹페이지를 보고 있을 때는 데이터 및 알림 페이로드를 페이지에서 직접 수신할 수 있습니다.

웹 모듈식 API

// Handle incoming messages. Called when:
// - a message is received while the app has focus
// - the user clicks on an app notification created by a service worker
//   `messaging.onBackgroundMessage` handler.
import { getMessaging, onMessage } from "firebase/messaging";

const messaging = getMessaging();
onMessage(messaging, (payload) => {
  console.log('Message received. ', payload);
  // ...
});

웹 네임스페이스화된 API

// Handle incoming messages. Called when:
// - a message is received while the app has focus
// - the user clicks on an app notification created by a service worker
//   `messaging.onBackgroundMessage` handler.
messaging.onMessage((payload) => {
  console.log('Message received. ', payload);
  // ...
});

웹 앱이 백그라운드 상태일 때 메시지 처리

앱이 백그라운드 상태일 때 수신된 모든 메시지는 브라우저의 화면 알림을 트리거합니다. 앱 서버의 전송 요청이나 클라이언트의 서비스 워커 로직을 사용하여 제목, 클릭 동작 등의 알림 관련 옵션을 지정할 수 있습니다.

전송 요청에 알림 옵션 설정

앱 서버에서 알림 메시지를 전송하는 경우 FCM JavaScript API는 fcm_options.link 키를 지원합니다. 일반적으로 이 키는 웹 앱의 페이지로 설정됩니다.

https://fcm.googleapis.com//v1/projects/<YOUR-PROJECT-ID>/messages:send
Content-Type: application/json
Authorization: bearer <YOUR-ACCESS-TOKEN>

{
  "message": {
    "token": "eEz-Q2sG8nQ:APA91bHJQRT0JJ...",
    "notification": {
      "title": "Background Message Title",
      "body": "Background message body"
    },
    "webpush": {
      "fcm_options": {
        "link": "https://dummypage.com"
      }
    }
  }
}

링크 값이 브라우저 탭에 이미 열려 있는 페이지를 가리키면 알림을 클릭할 때 해당 탭이 포그라운드로 전환됩니다. 페이지가 열려 있지 않은 경우 알림을 클릭하면 새 탭에서 페이지가 열립니다.

데이터 메시지는 fcm_options.link를 지원하지 않으므로 모든 데이터 메시지에 알림 페이로드를 추가하는 것이 좋습니다. 서비스 워커를 사용하여 알림을 처리할 수도 있습니다.

알림과 데이터 메시지의 차이점에 대한 설명은 메시지 유형을 참조하세요.

서비스 워커에서 알림 옵션 설정

데이터 메시지의 경우 서비스 워커에서 알림 옵션을 설정할 수 있습니다. 우선 서비스 워커에서 앱을 초기화합니다.

웹 모듈식 API

import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging/sw";

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
const firebaseApp = initializeApp({
  apiKey: 'api-key',
  authDomain: 'project-id.firebaseapp.com',
  databaseURL: 'https://project-id.firebaseio.com',
  projectId: 'project-id',
  storageBucket: 'project-id.appspot.com',
  messagingSenderId: 'sender-id',
  appId: 'app-id',
  measurementId: 'G-measurement-id',
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = getMessaging(firebaseApp);

웹 네임스페이스화된 API

// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here. Other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js');

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp({
  apiKey: 'api-key',
  authDomain: 'project-id.firebaseapp.com',
  databaseURL: 'https://project-id.firebaseio.com',
  projectId: 'project-id',
  storageBucket: 'project-id.appspot.com',
  messagingSenderId: 'sender-id',
  appId: 'app-id',
  measurementId: 'G-measurement-id',
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();

옵션을 설정하려면 firebase-messaging-sw.js에서 onBackgroundMessage를 호출하세요. 이 예시에서는 제목, 본문, 아이콘 필드가 있는 알림을 만듭니다.

웹 모듈식 API

import { getMessaging } from "firebase/messaging/sw";
import { onBackgroundMessage } from "firebase/messaging/sw";

const messaging = getMessaging();
onBackgroundMessage(messaging, (payload) => {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

  self.registration.showNotification(notificationTitle,
    notificationOptions);
});

웹 네임스페이스화된 API

messaging.onBackgroundMessage((payload) => {
  console.log(
    '[firebase-messaging-sw.js] Received background message ',
    payload
  );
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

  self.registration.showNotification(notificationTitle, notificationOptions);
});

알림 권장사항

웹용 푸시 메시지를 다루는 데 익숙하다면 좋은 알림 시스템의 조건에 관한 대략적인 가이드를 읽어 보셨을 것입니다. 웹용 FCM을 통해 알림을 전송하려는 개발자가 가장 중요하게 고려할 사항은 정확성과 관련성입니다. 알림의 정확성과 관련성을 유지하기 위해 구체적으로 다음과 같은 사항이 권장됩니다.

  • 아이콘 필드를 사용하여 의미 있는 이미지를 전송하세요. 대체로 이 이미지는 사용자가 바로 알아볼 수 있는 회사 또는 앱 로고여야 합니다. 채팅 애플리케이션이라면 발신자의 프로필 이미지일 수도 있습니다.
  • 제목 필드를 사용하여 메시지의 성격을 정확히 표현하세요. 예를 들어 '재영님의 회신'은 '새 메시지'보다 정확한 정보를 전해 줍니다. 이 귀중한 공간에 회사 이름이나 앱 이름을 넣지 마세요. 이름을 넣는 대신 아이콘을 사용하세요.
  • 알림 제목 또는 본문을 웹사이트 이름이나 도메인을 표시하는 데 사용하지 마세요. 알림에 이미 도메인 이름이 포함되어 있습니다.
  • fcm_options.link를 추가하세요. 일반적으로 사용자가 웹 앱을 브라우저에 다시 띄우도록 링크를 제공하는 것이 목적입니다. 드물지만 전달해야 하는 정보가 알림 창에 모두 표시되는 경우에는 링크가 필요하지 않을 수도 있습니다.