在 JavaScript 用戶端接收訊息

訊息的行為有所不同,取決於頁面是在前台(具有焦點)、還是在後台、隱藏在其他選項卡後面或完全關閉。在所有情況下,頁面都必須處理onMessage回調,但在背景情況下,您可能還需要處理onBackgroundMessage或設定顯示通知以允許使用者將您的 Web 應用程式帶入前台。

應用程式狀態通知數據兩個都
前景onMessage onMessage onMessage
背景(服務人員) onBackgroundMessage (自動顯示顯示通知) onBackgroundMessage onBackgroundMessage (自動顯示顯示通知)

JavaScript快速入門範例示範了接收訊息所需的所有程式碼。

當您的網頁應用程式位於前台時處理訊息

為了接收onMessage事件,您的應用程式必須在firebase-messaging-sw.js中定義 Firebase 訊息服務工作執行緒。或者,您可以透過getToken(): Promise<string>

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

當您的網頁應用程式在背景時處理訊息

應用程式在背景時收到的所有訊息都會觸發瀏覽器中的顯示通知。您可以在來自應用程式伺服器的傳送請求中或使用用戶端上的服務工作執行緒邏輯指定此通知的選項,例如標題或按一下操作。

在發送請求中設定通知選項

對於從應用程式伺服器發送的通知訊息,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": {
    "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 處理通知。

有關通知訊息和資料訊息之間差異的說明,請參閱訊息類型

在 Service Worker 中設定通知選項

對於資料訊息,您可以在 Service Worker 中設定通知選項。首先,在 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();

若要設定選項,請在firebase-messaging-sw.js中呼叫onBackgroundMessage 。在此範例中,我們建立一個包含標題、正文和圖示欄位的通知。

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 for Web 發送通知的開發人員來說,最重要的考慮因素是準確性和相關性。以下是一些確保通知準確且相關的具體建議:

  • 使用圖示欄位發送有意義的圖像。對於許多用例,這應該是用戶立即識別的公司或應用程式徽標。或者,對於聊天應用程序,它可能是發送用戶的個人資料圖像。
  • 使用標題欄位來表達訊息的精確性質。例如,「吉米回覆」比「新訊息」傳達更精確的訊息。不要將這個寶貴的空間用於您的公司或應用程式名稱 - 請使用該圖示來實現此目的。
  • 請勿使用通知標題或正文來顯示您的網站名稱或網域名稱;通知已包含您的網域。
  • 新增fcm_options.link ,通常用於將使用者連結回您的 Web 應用程式並將其置於瀏覽器中的焦點。在極少數情況下,您需要傳達的所有訊息都可以放入通知中,您可能不需要連結。