Join us for Firebase Summit on November 10, 2021. Tune in to learn how Firebase can help you accelerate app development, release with confidence, and scale with ease. Register

在 JavaScript 客戶端中接收消息

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

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

JavaScript的快速啟動示例演示了接收郵件所需的所有代碼。

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

為了收到onMessage事件,您的應用程序必須定義在火力地堡通訊服務工作者firebase-messaging-sw.js 。或者,也可以通過提供一種現有服務工人將SDK getToken(): Promise<string>

網頁版 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);

網頁版 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.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.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();

當您的應用程序處於前台時(用戶當前正在查看您的網頁),您可以直接在頁面中接收數據和通知負載。

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

網頁版 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 應用程序在後台時處理消息

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

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

對於從應用服務器發送的通知消息,在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 中初始化您的應用程序:

網頁版 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);

網頁版 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.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.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();

設置選項,呼叫onBackgroundMessagefirebase-messaging-sw.js 。在這個例子中,我們創建了一個帶有標題、正文和圖標字段的通知。

網頁版 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);
});

網頁版 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應用程序,並把它聚焦在瀏覽器中。在極少數情況下,您需要傳達的所有信息都可以放入通知中,您可能不需要鏈接。