| Выберите платформу: | iOS+ Android Web Flutter Unity C++ |
Поведение сообщений различается в зависимости от того, находится ли страница на переднем плане (имеет фокус) или в фоновом режиме, скрыта за другими вкладками или полностью закрыта. Во всех случаях страница должна обрабатывать обратный вызов onMessage , но в фоновом режиме может также потребоваться обработка onBackgroundMessage или настройка отображения уведомлений, позволяющих пользователю перевести ваше веб-приложение на передний план.
| Состояние приложения | Уведомление | Данные | Оба |
|---|---|---|---|
| Передний план | onMessage | onMessage | onMessage |
| Предыстория (работник сферы услуг) | onBackgroundMessage (отображает уведомление автоматически) | onBackgroundMessage | onBackgroundMessage (отображает уведомление автоматически) |
В приведенном примере быстрого запуска на JavaScript демонстрируется весь код, необходимый для приема сообщений.
Обрабатывайте сообщения, когда ваше веб-приложение находится на переднем плане.
In order to receive the onMessage event, your app must define the Firebase messaging service worker in firebase-messaging-sw.js . Alternatively, you can provide an existing service worker to the SDK through getToken(): Promise<string> .
Web
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
// 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. // Replace 10.13.2 with latest version of the Firebase JS SDK. importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-app-compat.js'); importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-messaging-compat.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
// 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
// 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); // ... });
Обрабатывайте сообщения, когда ваше веб-приложение работает в фоновом режиме.
All messages received while the app is in the background trigger a display notification in the browser. You can specify options for this notification, such as title or click action, either in the send request from your app server, or using service worker logic on the client.
Настройте параметры уведомлений в запросе на отправку.
Для уведомлений, отправляемых с сервера приложений, JavaScript API FCM поддерживает ключ fcm_options.link . Обычно он устанавливается на страницу вашего веб-приложения:
https://fcm.googleapis.com/v1/projects/<YOUR-PROJECT-ID>/messages:send
Content-Type: application/json
Authorization: bearer <YOUR-ACCESS-TOKEN>
{
"message": {
,
"notification": {
"title": "Background Message Title",
"body": "Background message body"
},
"webpush": {
"fcm_options": {
"link": "https://dummypage.com"
}
}
}
}
If the link value points to a page that is already open in a browser tab, clicking the notification brings that tab into the foreground. If the page is not already open, a notification click opens the page in a new tab.
Because data messages don't support fcm_options.link , you are recommended to add a notification payload to all data messages. Alternatively, you can handle notifications using the service worker.
Для объяснения различий между уведомлениями и сообщениями данных см. раздел «Типы сообщений» .
Настройте параметры уведомлений в сервис-воркере.
Для уведомлений о сообщениях с данными вы можете настроить параметры в сервис-воркере. Сначала инициализируйте ваше приложение в сервис-воркере:
Web
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
// 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. // Replace 10.13.2 with latest version of the Firebase JS SDK. importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-app-compat.js'); importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-messaging-compat.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();
Чтобы задать параметры, вызовите onBackgroundMessage в firebase-messaging-sw.js . В этом примере мы создаём уведомление с полями title, body и icon.
Web
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); });
Web
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); });
Рекомендации по использованию уведомлений
For developers sending notifications through FCM for Web, the most important considerations are precision and relevance. Here are some specific recommendations for keeping your notifications precise and relevant:
- Use the icon field to send a meaningful image. For many use cases, this should be a company or app logo that your users immediately recognize. Or, for a chat application, it might be the sending user's profile image.
- Use the title field to express the precise nature of the message. For example, "Jimmy replied" conveys more precise information than "New message." Don't use this valuable space for your company or app name — use the icon for that purpose.
- Не используйте заголовок или текст уведомления для отображения названия вашего веб-сайта или домена; уведомления уже содержат ваше доменное имя.
- Add
fcm_options.link, usually to link the user back to your web app and bring it into focus in the browser. In rare cases where all the information you need to convey can be fit into the notification, you might not need a link.