| בחירת פלטפורמה: | iOS+ Android אינטרנט Flutter Unity C++ |
ההתנהגות של ההודעות משתנה בהתאם למצב של הדף: אם הוא בחזית (במוקד), ברקע, מוסתר מאחורי כרטיסיות אחרות או סגור לגמרי. בכל המקרים, הדף צריך לטפל בקריאה החוזרת (callback) של onMessage, אבל במקרים של רקע, יכול להיות שיהיה צורך לטפל גם ב-onBackgroundMessage או להגדיר את ההתראה שמוצגת כדי לאפשר למשתמש להעביר את אפליקציית האינטרנט לחזית.
| מצב האפליקציה | התראה | נתונים | שניהם |
|---|---|---|---|
| חזית | onMessage |
onMessage |
onMessage |
| ברקע (service worker) | onBackgroundMessage (התראה שמוצגת באופן אוטומטי) |
onBackgroundMessage |
onBackgroundMessage (התראה שמוצגת באופן אוטומטי) |
הקוד לדוגמה ב-JavaScript להפעלה מהירה מדגים את כל הקוד שנדרש כדי לקבל הודעות.
טיפול בהודעות כשאפליקציית האינטרנט פועלת בחזית
כדי לקבל את האירוע onMessage, האפליקציה צריכה להגדיר את ה-service worker של העברת ההודעות ב-Firebase ב-firebase-messaging-sw.js.
לחלופין, אתם יכולים לספק ל-SDK קובץ service worker קיים באמצעות 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 13.0.0 with latest version of the Firebase JS SDK. importScripts('https://www.gstatic.com/firebasejs/13.0.0/firebase-app-compat.js'); importScripts('https://www.gstatic.com/firebasejs/13.0.0/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();
כשהאפליקציה פועלת בחזית (המשתמש צופה בדף האינטרנט), אפשר לקבל נתונים ומטענים ייעודיים (payloads) של התראות ישירות בדף.
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); // ... });
טיפול בהודעות כשאפליקציית האינטרנט פועלת ברקע
כל ההודעות שמתקבלות כשהאפליקציה פועלת ברקע מפעילות התראה שמוצגת בדפדפן. אתם יכולים לציין אפשרויות להתראה הזו, כמו כותרת או פעולת קליק, בבקשת השליחה משרת האפליקציה או באמצעות לוגיקה של Service Worker בלקוח.
הגדרת אפשרויות ההתראות בבקשת השליחה
בהודעות שנשלחות משרת האפליקציה, ה-API של FCM ב-JavaScript תומך במפתח 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"
}
}
}
}
אם ערך הקישור מפנה לדף שכבר פתוח בכרטיסייה בדפדפן, לחיצה על ההתראה תעביר את הכרטיסייה הזו לחזית. אם הדף לא פתוח, לחיצה על ההתראה תפתח את הדף בכרטיסייה חדשה.
הודעות נתונים לא תומכות ב-fcm_options.link, לכן מומלץ להוסיף מטען ייעודי (payload) של התראה לכל הודעות הנתונים. לחלופין, אתם יכולים לטפל בהתראות באמצעות ה-service worker.
הסבר על ההבדל בין הודעות התראה להודעות נתונים מופיע במאמר סוגי הודעות.
הגדרת אפשרויות ההתראות ב-Service Worker
בהודעות נתונים, אפשר להגדיר אפשרויות התראה ב-service worker. קודם, מאתחלים את האפליקציה ב-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 13.0.0 with latest version of the Firebase JS SDK. importScripts('https://www.gstatic.com/firebasejs/13.0.0/firebase-app-compat.js'); importScripts('https://www.gstatic.com/firebasejs/13.0.0/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.
בדוגמה הזו אנחנו יוצרים התראה עם שדות של כותרת, גוף וסמל.
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); });
שיטות מומלצות לשימוש בהתראות
למפתחים ששולחים התראות דרך FCM לאינטרנט, השיקולים הכי חשובים הם דיוק ורלוונטיות. הנה כמה המלצות ספציפיות שיעזרו לכם לשמור על התראות מדויקות ורלוונטיות:
- כדי לשלוח תמונה משמעותית, משתמשים בשדה הסמל. במקרים רבים, התמונה צריכה להיות לוגו של חברה או אפליקציה שהמשתמשים מזהים מיד. באפליקציית צ'אט, יכול להיות שזו תמונת הפרופיל של המשתמש ששלח את ההודעה.
- בשדה הכותרת, ציינו את המהות המדויקת של ההודעה. לדוגמה, "יוסי ענה" מעביר מידע מדויק יותר מאשר "הודעה חדשה". אל תשתמשו במקום החשוב הזה לשם החברה או האפליקציה – השתמשו בסמל למטרה הזו.
- אל תשתמשו בכותרת או בגוף ההתראה כדי להציג את שם האתר או הדומיין שלכם. ההתראות כבר מכילות את שם הדומיין.
- מוסיפים את
fcm_options.link, בדרך כלל כדי לקשר את המשתמש חזרה לאפליקציית האינטרנט ולהעביר אותה למיקוד בדפדפן. במקרים נדירים שבהם כל המידע שאתם צריכים להעביר נכנס להתראה, יכול להיות שלא תצטרכו קישור.