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

انتخاب پلاتفرم: iOS+ Android Web 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 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);
  // ...
});

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

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

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

برای پیام‌های اعلان ارسال‌شده از سرور برنامه، 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 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 را اضافه کنید، معمولاً برای پیوند دادن کاربر به برنامه وب و قرار دادن آن در کانون توجه در مرورگر. در موارد نادری که تمام اطلاعاتی که باید منتقل کنید در اعلان جا می‌شود، ممکن است به پیوند نیاز نداشته باشید.