دریافت پیام در «برنامه‌های وب»

انتخاب پلاتفرم: iOS+ Android وب Flutter Unity C++


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

وضعیت برنامه اعلان Data هردو
پیش‌زمینه onMessage onMessage onMessage
پس‌زمینه (عامل خدماتی) onBackgroundMessage (اعلان نمایش به‌طور خودکار نشان داده می‌شود) onBackgroundMessage onBackgroundMessage (اعلان نمایش به‌طور خودکار نشان داده می‌شود)

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

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

برای دریافت رویداد onMessage، برنامه‌تان باید کارگر سرویس پیام‌رسانی Firebase را در firebase-messaging-sw.js تعریف کند. یا می‌توانید ازطریق 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 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": {
        ,
        "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 برای وب اعلان ارسال می‌کنند، مهم‌ترین ملاحظات دقت و مرتبط بودن است. در اینجا چند توصیه خاص برای دقیق و مرتبط نگه داشتن اعلان‌هایتان آورده شده است:

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