קבלת הודעות באפליקציות אינטרנט

בחירת פלטפורמה: 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();

כשהאפליקציה פועלת בחזית (המשתמש צופה בדף האינטרנט שלכם), אתם יכולים לקבל נתונים ומטענים ייעודיים (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.
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 בלקוח.

הגדרת אפשרויות ההתראות בבקשת השליחה

במקרה של הודעות התראה שנשלחות משרת האפליקציה, JavaScript API תומך במפתח FCMfcm_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 for Web, השיקולים הכי חשובים הם דיוק ורלוונטיות. הנה כמה המלצות ספציפיות שיעזרו לכם לשמור על התראות מדויקות ורלוונטיות:

  • כדי לשלוח תמונה משמעותית, משתמשים בשדה הסמל. במקרים רבים, התמונה צריכה להיות לוגו של חברה או אפליקציה שהמשתמשים מזהים מיד. באפליקציית צ'אט, יכול להיות שזו תמונת הפרופיל של המשתמש ששלח את ההודעה.
  • בשדה שם הפריט צריך לציין את האופי המדויק של ההודעה. לדוגמה, "יוסי ענה" מעביר מידע מדויק יותר מאשר "הודעה חדשה". אל תשתמשו במקום הזה כדי להציג את שם החברה או האפליקציה – לשם כך יש את הסמל.
  • אל תשתמשו בכותרת או בגוף ההתראה כדי להציג את שם האתר או הדומיין שלכם. ההתראות כבר מכילות את שם הדומיין.
  • מוסיפים את fcm_options.link, בדרך כלל כדי לקשר את המשתמש חזרה לאפליקציית האינטרנט ולהעביר אותה למיקוד בדפדפן. במקרים נדירים שבהם כל המידע שאתם צריכים להעביר נכנס להתראה, יכול להיות שלא תצטרכו קישור.