تلقّي الرسائل في برنامج JavaScript

يختلف سلوك الرسائل حسب سواء كانت الصفحة في المقدّمة (مع التركيز عليها) أو مخفية خلف علامات تبويب أخرى، أو إغلاقها تمامًا. في جميع الحالات، يجب أن تتعامل الصفحة مع onMessage ولكن في الحالات الخلفية، قد تحتاج أيضًا إلى التعامل onBackgroundMessage أو ضبط إشعار العرض للسماح للمستخدم بجلب تطبيق الويب في المقدمة.

حالة التطبيق الإشعار البيانات كلاهما
لون الواجهة onMessage onMessage onMessage
الخلفية (مشغّل الخدمات) onBackgroundMessage (يتم عرض الإشعار المعروض تلقائيًا) onBackgroundMessage onBackgroundMessage (يتم عرض الإشعار المعروض تلقائيًا)

يوضح نموذج البدء السريع في JavaScript جميع الرموز المطلوبة لاستلام الرسائل.

التعامل مع الرسائل عندما يكون تطبيق الويب في المقدّمة

لتلقّي حدث "onMessage"، يجب أن يحدّد تطبيقك عامل خدمة المراسلة على Firebase في firebase-messaging-sw.js. يمكنك بدلاً من ذلك تزويد حزمة تطوير البرامج (SDK) بأحد مشغِّلي الخدمات الحاليين من خلال 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.
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

// 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);
  // ...
});

التعامل مع الرسائل عندما يكون تطبيق الويب في الخلفية

تؤدي جميع الرسائل المُستلَمة أثناء تشغيل التطبيق في الخلفية إلى عرض الشاشة. في المتصفح. يمكنك تحديد خيارات لهذا الإشعار، مثل العنوان أو إجراء النقر، سواء في طلب الإرسال من خادم التطبيق أو استخدام منطق مشغّل الخدمات على العميل.

ضبط خيارات الإشعار في طلب الإرسال

بالنسبة إلى رسائل الإشعارات المُرسَلة من خادم التطبيقات، تتيح خدمة "المراسلة عبر السحابة الإلكترونية من Firebase" تتيح واجهة برمجة تطبيقات 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": {
    "token": "eEz-Q2sG8nQ:APA91bHJQRT0JJ...",
    "notification": {
      "title": "Background Message Title",
      "body": "Background message body"
    },
    "webpush": {
      "fcm_options": {
        "link": "https://dummypage.com"
      }
    }
  }
}

إذا كانت قيمة الرابط توجّه إلى صفحة مفتوحة في علامة تبويب متصفّح، يؤدي النقر على الإشعار إلى ظهور علامة التبويب هذه في المقدمة. وإذا لم تكن الصفحة مفتوحة بالفعل، يؤدي النقر على إشعار إلى فتح الصفحة في .

بما أنّ رسائل البيانات لا تتوافق مع fcm_options.link، نقترح عليك ما يلي: إضافة حمولة الإشعارات إلى جميع رسائل البيانات بدلاً من ذلك، يمكنك التعامل مع الإشعارات باستخدام مشغّل الخدمات.

لمزيد من المعلومات عن الفرق بين الإشعارات ورسائل البيانات، يمكنك الاطّلاع على أنواع الرسائل:

إعداد خيارات الإشعارات في مشغّل الخدمات

بالنسبة إلى رسائل البيانات، يمكنك ضبط خيارات الإشعارات في مشغّل الخدمات. أولاً، عليك إعداد تطبيقك في مشغّل الخدمات:

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.
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

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);
});

أفضل الممارسات للإشعارات

إذا كنت على دراية بخدمة الدفع الفوري للويب، فربما تكون قد قرأت الإرشادات العامة حول عناصر إنشاء الإشعارات الجيدة. بالنسبة إلى المطوّرين الذين يرسلون الإشعارات من خلال خدمة "المراسلة عبر السحابة الإلكترونية من Firebase" للويب، من أهم الاعتبارات هما الدقة والصلة. فيما يلي بعض التوصيات المحددة للاحتفاظ الإشعارات الدقيقة وذات الصلة بالموضوع:

  • استخدِم حقل الرمز لإرسال صورة ذات معنى. بالنسبة للعديد من حالات الاستخدام، يجب أن يكون شعار شركة أو تطبيق يعرفه المستخدمون على الفور. أو، بالنسبة إلى تطبيق دردشة، فقد تكون صورة الملف الشخصي للمستخدم المرسِل.
  • استخدم حقل العنوان للتعبير عن طبيعة الرسالة الدقيقة. على سبيل المثال: "رد جيمي" ينقل معلومات أكثر دقة من "رسالة جديدة". عدم الاستخدام هذه المساحة القيّمة لشركتك أو اسم تطبيقك - استخدم الرمز لهذا الغرض.
  • لا تستخدِم عنوان الإشعار أو نصه لعرض اسم موقعك الإلكتروني أو مجال؛ تحتوي الإشعارات بالفعل على اسم نطاقك.
  • عليك إضافة fcm_options.link، وعادةً ما يتم ربط المستخدم بتطبيق الويب وجلب موضع التركيز في المتصفح. في حالات نادرة، عندما تحتاج إلى إدخال جميع المعلومات لنقلها في الإشعار، فقد لا تحتاج إلى رابط.