Catch up on everything announced at Firebase Summit, and learn how Firebase can help you accelerate app development and run your app with confidence. Learn More

在 JavaScript 客戶端中接收消息

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

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

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

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

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

為了接收onMessage事件,您的應用必須在firebase-messaging-sw.js中定義 Firebase 消息傳遞服務工作者。或者,您可以通過getToken(): Promise<string>向 SDK 提供現有的 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/9.2.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/9.2.0/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);
  // ...
});

當您的 Web 應用程序在後台時處理消息

應用程序在後台時收到的所有消息都會在瀏覽器中觸發顯示通知。您可以在來自應用服務器的發送請求中或使用客戶端上的服務工作線程邏輯指定此通知的選項,例如標題或單擊操作。

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

對於從應用服務器發送的通知消息,FCM JavaScript API 支持fcm_options.link鍵。通常,這設置為您的 Web 應用程序中的一個頁面:

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 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/9.2.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/9.2.0/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 firebase-messaging-sw.js onBackgroundMessage在這個例子中,我們創建了一個帶有標題、正文和圖標字段的通知。

Web version 9

import { getMessaging } from "firebase/messaging";
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);
});

通知的最佳做法

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

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