Catch up on highlights from Firebase at Google I/O 2023. Learn more

รับข้อความในไคลเอนต์ JavaScript

ลักษณะการทำงานของข้อความจะแตกต่างกันไปโดยขึ้นอยู่กับว่าหน้านั้นอยู่เบื้องหน้า (มีโฟกัส) หรืออยู่เบื้องหลัง ซ่อนอยู่หลังแท็บอื่น หรือปิดสนิท ในทุกกรณี เพจต้องจัดการการเรียกกลับ onMessage แต่ในกรณีเบื้องหลัง คุณอาจต้องจัดการ onBackgroundMessage หรือกำหนดค่าการแจ้งเตือนที่แสดงเพื่ออนุญาตให้ผู้ใช้นำเว็บแอปของคุณไปที่เบื้องหน้า

สถานะแอป การแจ้งเตือน ข้อมูล ทั้งคู่
เบื้องหน้า onMessage onMessage onMessage
ความเป็นมา (พนักงานบริการ) onBackgroundMessage (แสดงการแจ้งเตือนโดยอัตโนมัติ) onBackgroundMessage onBackgroundMessage (แสดงการแจ้งเตือนโดยอัตโนมัติ)

ตัวอย่างการเริ่มใช้งานด่วน ของ JavaScript จะสาธิตโค้ดทั้งหมดที่จำเป็นในการรับข้อความ

จัดการข้อความเมื่อเว็บแอปของคุณอยู่เบื้องหน้า

ในการรับเหตุการณ์ onMessage แอปของคุณต้องกำหนด Firebase messaging service worker ใน firebase-messaging-sw.js หรือคุณสามารถจัดหาพนักงานบริการที่มีอยู่ให้กับ SDK ผ่าน 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 ขอแนะนำให้คุณเพิ่มเพย์โหลดการแจ้งเตือนในข้อความข้อมูลทั้งหมด หรือคุณสามารถจัดการการแจ้งเตือนโดยใช้พนักงานบริการ

สำหรับคำอธิบายความแตกต่างระหว่างข้อความแจ้งเตือนและข้อมูล โปรดดู ที่ ประเภทข้อความ

การตั้งค่าตัวเลือกการแจ้งเตือนในพนักงานบริการ

สำหรับข้อความข้อมูล คุณสามารถตั้งค่าตัวเลือกการแจ้งเตือนในพนักงานบริการ ขั้นแรก เริ่มต้นแอปของคุณในพนักงานบริการ:

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

หากต้องการตั้งค่าตัวเลือก ให้เรียก onBackgroundMessage ใน firebase-messaging-sw.js ในตัวอย่างนี้ เราสร้างการแจ้งเตือนด้วยฟิลด์ชื่อ เนื้อหา และไอคอน

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 สำหรับเว็บ ข้อควรพิจารณาที่สำคัญที่สุดคือความแม่นยำและความเกี่ยวข้อง ต่อไปนี้เป็นคำแนะนำเฉพาะบางประการเพื่อให้การแจ้งเตือนของคุณแม่นยำและตรงประเด็น:

  • ใช้ช่องไอคอนเพื่อส่งภาพที่สื่อความหมาย สำหรับกรณีการใช้งานหลายๆ กรณี นี่ควรเป็นโลโก้ของบริษัทหรือแอปที่ผู้ใช้ของคุณจำได้ทันที หรือสำหรับแอปพลิเคชันแชท อาจเป็นรูปภาพโปรไฟล์ของผู้ใช้ที่ส่ง
  • ใช้ฟิลด์ชื่อเพื่อแสดงลักษณะที่ชัดเจนของข้อความ ตัวอย่างเช่น "จิมมี่ตอบกลับ" สื่อถึงข้อมูลที่แม่นยำกว่า "ข้อความใหม่" อย่าใช้พื้นที่อันมีค่านี้สำหรับบริษัทหรือชื่อแอปของคุณ — ใช้ไอคอนเพื่อจุดประสงค์นั้น
  • อย่าใช้ชื่อหรือเนื้อหาการแจ้งเตือนเพื่อแสดงชื่อเว็บไซต์หรือโดเมนของคุณ การแจ้งเตือนมีชื่อโดเมนของคุณอยู่แล้ว
  • เพิ่ม fcm_options.link โดยปกติแล้วเพื่อลิงก์ผู้ใช้กลับไปที่เว็บแอปของคุณ และทำให้ผู้ใช้สนใจในเบราว์เซอร์ ในบางกรณีซึ่งไม่บ่อยนักที่ข้อมูลทั้งหมดที่คุณต้องการสื่อสามารถใส่ลงในการแจ้งเตือนได้ คุณอาจไม่ต้องการลิงก์