在 JavaScript 用戶端中接收訊息

郵件行為因 網頁是在前景 (聚焦) 還是在背景播放 顯示在其他分頁後或完全關閉無論如何,網頁都必須處理 onMessage敬上 回呼,但在背景中,您可能也需要處理 onBackgroundMessage 或設定顯示通知,讓使用者可以 移至前景

應用程式狀態 通知 資料 兩者並用
前景 onMessage onMessage onMessage
背景 (服務工作處理程序) onBackgroundMessage (自動顯示通知) onBackgroundMessage onBackgroundMessage (自動顯示通知)

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

在網頁應用程式在前景運作時處理訊息

為了接收 onMessage 事件,應用程式必須定義 「firebase-messaging-sw.js」中的 Firebase 訊息傳遞 Service Worker。 您也可以透過以下方式,將現有的 Service Worker 提供給 SDK: 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.
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

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

在網頁應用程式在背景執行時處理訊息

應用程式在背景執行時收到的所有訊息都會觸發顯示畫面 。您可以為這則通知指定選項 例如在應用程式伺服器傳送要求中 或在用戶端使用 Service Worker 邏輯

在傳送要求中設定通知選項

如果是從應用程式伺服器傳送的通知訊息,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

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.
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

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,通常用於將使用者重新連結至網頁應用程式 瀏覽器焦點在極少數情況下,您需要所有必要資訊 通知可以融入通知 您不一定要有連結