پیام ها را در یک کلاینت جاوا اسکریپت دریافت کنید

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

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

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

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

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

Web modular API

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 namespaced API

// 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 modular API

// 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 namespaced API

// 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": {
    "token": "eEz-Q2sG8nQ:APA91bHJQRT0JJ...",
    "notification": {
      "title": "Background Message Title",
      "body": "Background message body"
    },
    "webpush": {
      "fcm_options": {
        "link": "https://dummypage.com"
      }
    }
  }
}

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

از آنجایی که پیام‌های داده fcm_options.link پشتیبانی نمی‌کنند، توصیه می‌شود یک بار اعلان به همه پیام‌های داده اضافه کنید. از طرف دیگر، می‌توانید اعلان‌ها را با استفاده از سرویس‌کار مدیریت کنید.

برای توضیح تفاوت بین پیام‌های اعلان و داده، به انواع پیام مراجعه کنید.

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

برای پیام‌های داده، می‌توانید گزینه‌های اعلان را در سرویس‌کار تنظیم کنید. ابتدا برنامه خود را در Service Worker مقداردهی اولیه کنید:

Web modular API

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 namespaced API

// 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 modular API

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 namespaced API

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