Firebase is back at Google I/O on May 10! Register now

在 JavaScript 客戶端中接收消息

透過集合功能整理內容 你可以依據偏好儲存及分類內容。

消息的行為取決於頁面是在前台(有焦點),還是在後台,隱藏在其他選項卡後面,或者完全關閉。在所有情況下,頁面都必須處理onMessage回調,但在後臺情況下,您可能還需要處理onBackgroundMessage或配置顯示通知以允許用戶將您的 Web 應用程序帶到前台。

應用狀態通知數據兩個都
前景onMessage onMessage onMessage
背景(服務工作者) onBackgroundMessage (顯示通知自動顯示) onBackgroundMessage onBackgroundMessage (顯示通知自動顯示)

JavaScript快速入門示例演示了接收消息所需的所有代碼。

當您的 Web 應用程序位於前台時處理消息

為了接收onMessage事件,您的應用必須在firebase-messaging-sw.js中定義 Firebase 消息傳遞服務工作者。或者,您可以通過getToken(): Promise<string>向 SDK 提供現有的服務工作者。

Web version 9

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 version 8

// 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 version 9

// 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 version 8

// 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 處理通知。

有關通知消息和數據消息之間差異的說明,請參閱消息類型

在服務工作者中設置通知選項

對於數據消息,您可以在服務工作者中設置通知選項。首先,在服務工作者中初始化您的應用程序:

Web version 9

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 version 8

// 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 version 9

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 version 8

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

通知的最佳實踐

如果您熟悉 Web 的推送消息,您可能已經閱讀了關於什麼是好的通知的廣泛指南。對於通過 FCM for Web 發送通知的開發人員來說,最重要的考慮因素是準確性和相關性。以下是一些使您的通知準確且相關的具體建議:

  • 使用圖標字段發送有意義的圖像。對於許多用例,這應該是您的用戶可以立即識別的公司或應用程序徽標。或者,對於聊天應用程序,它可能是發送用戶的個人資料圖像。
  • 使用標題字段來表達消息的準確性質。例如,“Jimmy replyed”比“New message”傳達的信息更準確。不要將這個寶貴的空間用於您的公司或應用程序名稱 - 為此目的使用圖標。
  • 不要使用通知標題或正文來顯示您的網站名稱或域名;通知已包含您的域名。
  • 添加fcm_options.link ,通常用於將用戶鏈接回您的網絡應用程序並將其置於瀏覽器中。在極少數情況下,您需要傳達的所有信息都可以放入通知中,您可能不需要鏈接。