รับข้อความในเว็บแอป

เลือกแพลตฟอร์ม: iOS+ Android เว็บ Flutter Unity C++


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

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

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

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

หากต้องการรับเหตุการณ์ onMessage แอปต้องกำหนด Service Worker ของการรับส่งข้อความ 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.
// Replace 10.13.2 with latest version of the Firebase JS SDK.
importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-messaging-compat.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);
  // ...
});

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

ข้อความทั้งหมดที่ได้รับขณะที่แอปทำงานในเบื้องหลังจะทริกเกอร์การแสดง การแจ้งเตือนในเบราว์เซอร์ คุณระบุตัวเลือกสำหรับการแจ้งเตือนนี้ได้ เช่น ชื่อหรือการคลิกดำเนินการ ไม่ว่าจะในคำขอส่งจากเซิร์ฟเวอร์แอป หรือใช้ตรรกะของ Service Worker ในไคลเอ็นต์

ตั้งค่าตัวเลือกการแจ้งเตือนในคำขอส่ง

สำหรับข้อความแจ้งเตือนที่ส่งจากเซิร์ฟเวอร์ของแอป 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": {
        ,
        "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

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.
// Replace 10.13.2 with latest version of the Firebase JS SDK.
importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-messaging-compat.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 ซึ่งมักใช้เพื่อลิงก์ผู้ใช้กลับไปยังเว็บแอปและนำ มาไว้ที่โฟกัสในเบราว์เซอร์ ในบางกรณีที่พบไม่บ่อยนักซึ่งคุณสามารถใส่ข้อมูลทั้งหมดที่ต้องการสื่อสารลงในการแจ้งเตือนได้ คุณก็อาจไม่จำเป็นต้องมีลิงก์