ההתנהגות של ההודעות שונה בהתאם לשאלה אם הדף נמצא בחזית (במיקוד) או ברקע, מוסתר מאחורי כרטיסיות אחרות או סגור לחלוטין. בכל המקרים, הדף צריך לטפל בקריאה החוזרת onMessage
, אבל במקרים של רקע יכול להיות שיהיה צורך גם לטפל בקריאה החוזרת onBackgroundMessage
או להגדיר את התראת התצוגה כדי לאפשר למשתמש להעביר את אפליקציית האינטרנט לחזית.
מצב האפליקציה | התראה | נתונים | שניהם |
---|---|---|---|
חזית | onMessage |
onMessage |
onMessage |
רקע (service worker) | onBackgroundMessage (התראה על הצגה מוצגת באופן אוטומטי) |
onBackgroundMessage |
onBackgroundMessage (התראה על הצגה מוצגת באופן אוטומטי) |
הדוגמה להתחלה מהירה ב-JavaScript מדגימה את כל הקוד שנדרש לקבלת הודעות.
טיפול בהודעות כשאפליקציית האינטרנט פועלת בחזית
כדי לקבל את האירוע onMessage
, צריך להגדיר באפליקציה את 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 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();
כשהאפליקציה פועלת בחזית (המשתמש צופה כרגע בדף האינטרנט שלכם), אתם יכולים לקבל נתונים ומטענים ייעודיים (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 בלקוח.
הגדרת אפשרויות התראה בבקשת השליחה
במקרה של הודעות התראה שנשלחות משרת האפליקציה, 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
, מומלץ להוסיף מטען ייעודי (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 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
.
בדוגמה הזו, אנחנו יוצרים התראה עם שדות של כותרת, גוף וסמל.
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 for Web, השיקולים החשובים ביותר הם דיוק ורלוונטיות. ריכזנו כאן כמה המלצות ספציפיות שיעזרו לכם לוודא שההתראות מדויקות ורלוונטיות:
- משתמשים בשדה הסמל כדי לשלוח תמונה בעלת משמעות. במקרים רבים, התמונה צריכה להיות לוגו של חברה או אפליקציה שהמשתמשים מזהים מיד. או, באפליקציית צ'אט, יכול להיות שזו תמונת הפרופיל של המשתמש ששלח את ההודעה.
- בשדה שם הפריט צריך לציין את מהות ההודעה בצורה מדויקת. לדוגמה, ההודעה "ג'ימי השיב" מעבירה מידע מדויק יותר מההודעה "הודעה חדשה". אל תשתמשו במקום החשוב הזה לשם החברה או האפליקציה – השתמשו בסמל למטרה הזו.
- אל תשתמשו בכותרת או בגוף של ההתראה כדי להציג את שם האתר או הדומיין שלכם. ההתראות כבר מכילות את שם הדומיין.
- מוסיפים
fcm_options.link
, בדרך כלל כדי לקשר את המשתמש בחזרה לאפליקציית האינטרנט ולהעביר אותה למוקד בדפדפן. במקרים נדירים שבהם כל המידע שאתם צריכים להעביר נכנס להתראה, יכול להיות שלא תצטרכו קישור.