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

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

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

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

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

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

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

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

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

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 ซึ่งโดยปกติจะเชื่อมโยงผู้ใช้กลับไปที่เว็บแอปของคุณและเน้นไปที่เบราว์เซอร์ ในบางกรณีที่เกิดขึ้นไม่บ่อยนักที่ข้อมูลทั้งหมดที่คุณต้องการสื่อสามารถใส่ลงในการแจ้งเตือนได้ คุณอาจไม่จำเป็นต้องมีลิงก์