تلقّي الرسائل في برنامج 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);
  // ...
});

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

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

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

بالنسبة إلى رسائل الإشعارات المُرسَلة من خادم التطبيق، تتيح واجهة برمجة تطبيقات JavaScript للمراسلة عبر السحابة الإلكترونية من Firebase استخدام مفتاح 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، ويتم ذلك عادةً لربط المستخدم بتطبيق الويب مرة أخرى ولفت انتباه المستخدم إلى التطبيق في المتصفّح. في حالات نادرة عندما يمكن أن تتناسب كل المعلومات التي تحتاج إلى نقلها في الإشعار، قد لا تحتاج إلى رابط.