با استفاده از Firebase Cloud Messaging پیام ها را دریافت کنید

این راهنما نحوه تنظیم Firebase Cloud Messaging را در برنامه‌های موبایل و کلاینت وب شما شرح می‌دهد تا بتوانید پیام‌ها را به طور قابل اعتمادی دریافت کنید.

The behavior of messages differs depending on whether the page is in the foreground (has focus), or in the background, hidden behind other tabs, or completely closed. In all cases the page must handle the onMessage callback, but in background cases you may also need to handle onBackgroundMessage or configure the display notification to allow the user to bring your web app into the foreground.

حالت برنامه اعلان داده‌ها هر دو
پیش‌زمینه onMessage onMessage onMessage
پیشینه (کارگر خدماتی) onBackgroundMessage (نمایش خودکار اعلان‌ها) onBackgroundMessage onBackgroundMessage (نمایش خودکار اعلان‌ها)

نمونه شروع سریع جاوا اسکریپت، تمام کد مورد نیاز برای دریافت پیام‌ها را نشان می‌دهد.

مدیریت پیام‌ها زمانی که برنامه وب شما در پیش‌زمینه است

برای دریافت رویداد onMessage ، برنامه شما باید سرویس دهنده پیام رسانی Firebase را در firebase-messaging-sw.js تعریف کند. همچنین می‌توانید یک سرویس دهنده موجود را از طریق getToken(): Promise<string> به SDK ارائه دهید.

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 10.13.2 with latest version of the Firebase JS SDK.
importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.13.2/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);
  // ...
});

مدیریت پیام‌ها وقتی برنامه وب شما در پس‌زمینه است

تمام پیام‌های دریافتی در حالی که برنامه در پس‌زمینه است، یک اعلان نمایش در مرورگر ایجاد می‌کنند. می‌توانید گزینه‌هایی برای این اعلان، مانند عنوان یا اقدام کلیک، یا در درخواست ارسال از سرور برنامه خود یا با استفاده از منطق سرویس‌دهنده در کلاینت، مشخص کنید.

گزینه‌های اعلان را در درخواست ارسال تنظیم کنید

برای پیام‌های اعلان ارسالی از سرور برنامه، API جاوا اسکریپت FCM از کلید 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 پشتیبانی نمی‌کنند، توصیه می‌شود یک بار اعلان به همه پیام‌های داده اضافه کنید. به عنوان یک روش جایگزین، می‌توانید اعلان‌ها را با استفاده از 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 10.13.2 with latest version of the Firebase JS SDK.
importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.13.2/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 برای وب اعلان‌ها را ارسال می‌کنند، مهم‌ترین ملاحظات دقت و مرتبط بودن است. در اینجا چند توصیه خاص برای دقیق و مرتبط نگه داشتن اعلان‌های شما ارائه شده است:

  • از فیلد آیکون برای ارسال یک تصویر معنادار استفاده کنید. در بسیاری از موارد استفاده، این تصویر باید لوگوی شرکت یا برنامه‌ای باشد که کاربران شما بلافاصله آن را تشخیص می‌دهند. یا برای یک برنامه چت، می‌تواند تصویر پروفایل کاربر فرستنده باشد.
  • از فیلد عنوان برای بیان ماهیت دقیق پیام استفاده کنید. برای مثال، «جیمی پاسخ داد» اطلاعات دقیق‌تری نسبت به «پیام جدید» منتقل می‌کند. از این فضای ارزشمند برای نام شرکت یا برنامه خود استفاده نکنید - از آیکون برای این منظور استفاده کنید.
  • از عنوان یا متن اعلان برای نمایش نام وب‌سایت یا دامنه خود استفاده نکنید؛ اعلان‌ها از قبل حاوی نام دامنه شما هستند.
  • fcm_options.link را اضافه کنید، معمولاً برای پیوند دادن کاربر به برنامه وب شما و قرار دادن آن در مرورگر. در موارد نادری که تمام اطلاعات مورد نیاز برای انتقال می‌توانند در اعلان جا شوند، ممکن است به پیوند نیازی نداشته باشید.