تلقّي الرسائل في تطبيقات الويب

اختيار النظام الأساسي: iOS+ Android الويب Flutter Unity C++‎


يختلف سلوك الرسائل حسب ما إذا كانت الصفحة في المقدّمة (أي أنّها محور التركيز) أو في الخلفية، أي مخفية خلف علامات تبويب أخرى أو مغلقة تمامًا. في جميع الحالات، يجب أن تتعامل الصفحة مع 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.
// 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();

عندما يكون تطبيقك في المقدّمة (أي عندما يشاهد المستخدم صفحة الويب الخاصة بك)، يمكنك تلقّي حمولات البيانات والإشعارات مباشرةً في الصفحة.

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

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

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

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

بالنسبة إلى رسائل الإشعارات المُرسَلة من خادم التطبيق، تتيح واجهة برمجة التطبيقات FCM 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": {
        ,
        "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.
// 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 للويب، فإنّ أهم الاعتبارات هي الدقة والملاءمة. فيما يلي بعض التوصيات المحددة للحفاظ على دقة الإشعارات وملاءمتها:

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