קבלת הודעות בלקוח JavaScript

התנהגות ההודעות משתנה בהתאם אם הדף נמצא בחזית (יש לו מיקוד), או ברקע, מוסתר מאחורי כרטיסיות אחרות או סגור לחלוטין. בכל המקרים הדף חייב לטפל בהתקשרות חוזרת onMessage , אך במקרים ברקע ייתכן שיהיה עליך לטפל onBackgroundMessage או להגדיר את התראת התצוגה כדי לאפשר למשתמש להביא את אפליקציית האינטרנט שלך לקדמת הבמה.

מצב האפליקציה הוֹדָעָה נתונים שניהם
חֲזִית onMessage onMessage onMessage
רקע (עובד שירות) onBackgroundMessage (הצג התראה מוצגת באופן אוטומטי) onBackgroundMessage onBackgroundMessage (הצג התראה מוצגת באופן אוטומטי)

דגימת ההתחלה המהירה של JavaScript מדגימה את כל הקוד הנדרש לקבלת הודעות.

טפל בהודעות כאשר אפליקציית האינטרנט שלך נמצאת בחזית

על מנת לקבל את אירוע onMessage , האפליקציה שלך חייבת להגדיר את עובד שירות ההודעות של Firebase ב- firebase-messaging-sw.js . לחלופין, אתה יכול לספק שירות עובד קיים ל-SDK דרך getToken(): Promise<string> .

Web modular API

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 namespaced API

// 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/8.10.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.1/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 modular API

// 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 namespaced API

// 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 , מומלץ להוסיף מטען הודעות לכל הודעות הנתונים. לחלופין, תוכל לטפל בהתראות באמצעות ה-Service Worker.

להסבר על ההבדל בין הודעות הודעה לנתונים, ראה סוגי הודעות .

הגדרת אפשרויות התראות ב-Service Worker

עבור הודעות נתונים, תוכל להגדיר אפשרויות התראות ב-Service Worker. ראשית, אתחל את האפליקציה שלך ב-Service Worker:

Web modular API

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 namespaced API

// 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/8.10.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.1/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();

כדי להגדיר אפשרויות, התקשר onBackgroundMessage ב- firebase-messaging-sw.js . בדוגמה זו, אנו יוצרים הודעה עם שדות כותרת, גוף וסמל.

Web modular API

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 namespaced API

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