메시지의 동작은 페이지가 포그라운드에 있는지(포커스가 있음), 백그라운드에 있는지, 다른 탭 뒤에 가려져 있는지 또는 완전히 닫혀 있는지에 따라 다릅니다. 모든 경우에 페이지는 onMessage
콜백을 처리해야 하지만 백그라운드의 경우 onBackgroundMessage
를 처리하거나 사용자가 웹 앱을 포그라운드로 가져올 수 있도록 표시 알림을 구성해야 할 수도 있습니다.
앱 상태 | 공고 | 데이터 | 둘 다 |
---|---|---|---|
전경 | onMessage | onMessage | onMessage |
배경(서비스 워커) | onBackgroundMessage (디스플레이 알림이 자동으로 표시됨) | onBackgroundMessage | onBackgroundMessage (디스플레이 알림이 자동으로 표시됨) |
JavaScript 빠른 시작 샘플 은 메시지를 수신하는 데 필요한 모든 코드를 보여줍니다.
웹 앱이 포그라운드에 있을 때 메시지 처리
onMessage
이벤트를 수신하려면 앱 firebase-messaging-sw.js
에서 Firebase 메시징 서비스 작업자를 정의해야 합니다. 또는 getToken(): Promise<string>
을 통해 기존 서비스 워커를 SDK에 제공할 수 있습니다.
Web version 9
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);
Web version 8
// 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/9.2.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/9.2.0/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();
앱이 포그라운드에 있을 때(사용자가 현재 웹 페이지를 보고 있을 때) 페이지에서 직접 데이터 및 알림 페이로드를 받을 수 있습니다.
Web version 9
// 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); // ... });
Web version 8
// 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
를 지원하지 않기 때문에 모든 데이터 메시지에 알림 페이로드를 추가하는 것이 좋습니다. 또는 서비스 워커를 사용하여 알림을 처리할 수 있습니다.
알림과 데이터 메시지의 차이점에 대한 설명은 메시지 유형 을 참조하십시오.
서비스 워커에서 알림 옵션 설정
데이터 메시지의 경우 서비스 워커에서 알림 옵션을 설정할 수 있습니다. 먼저 서비스 워커에서 앱을 초기화합니다.
Web version 9
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);
Web version 8
// 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/9.2.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/9.2.0/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 firebase-messaging-sw.js
onBackgroundMessage
를 호출하세요. 이 예에서는 제목, 본문 및 아이콘 필드가 있는 알림을 만듭니다.
Web version 9
import { getMessaging } from "firebase/messaging"; 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); });
Web version 8
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을 통해 알림을 보내는 개발자의 경우 가장 중요한 고려 사항은 정확성과 관련성입니다. 다음은 알림을 정확하고 관련성 있게 유지하기 위한 몇 가지 구체적인 권장 사항입니다.
- 아이콘 필드를 사용하여 의미있는 이미지를 보내십시오. 많은 사용 사례에서 이것은 사용자가 즉시 인식할 수 있는 회사 또는 앱 로고여야 합니다. 또는 채팅 애플리케이션의 경우 보내는 사용자의 프로필 이미지일 수 있습니다.
- 제목 필드를 사용하여 메시지의 정확한 특성을 표현하십시오. 예를 들어 "Jimmy reply"는 "New message"보다 더 정확한 정보를 전달합니다. 회사 또는 앱 이름에 이 귀중한 공간을 사용하지 말고 해당 용도로 아이콘을 사용하십시오.
- 알림 제목이나 본문을 사용하여 웹사이트 이름이나 도메인을 표시하지 마세요. 알림에 이미 도메인 이름이 포함되어 있습니다.
-
fcm_options.link
를 추가하여 일반적으로 사용자를 웹 앱에 다시 연결하고 브라우저에서 초점을 맞춥니다. 드물게 전달해야 하는 모든 정보가 알림에 적합할 수 있는 경우 링크가 필요하지 않을 수 있습니다.