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

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


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

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

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

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

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

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

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

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