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

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

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

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

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

หากต้องการรับเหตุการณ์ onMessage แอปของคุณต้องกำหนดโปรแกรมทำงานของบริการรับส่งข้อความของ Firebase ใน firebase-messaging-sw.js หรือจะให้ Service Worker ที่มีอยู่ทำงานให้กับ SDK ผ่าน getToken(): Promise<string> ก็ได้

Web

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

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

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

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

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

Web

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

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

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

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