| Chọn nền tảng: | iOS+ Android Web Flutter Unity C++ |
Hành vi của thông báo sẽ khác nhau tuỳ thuộc vào việc trang đang ở nền trước (đang được tập trung) hay ở nền sau, bị ẩn sau các thẻ khác hoặc đã đóng hoàn toàn. Trong mọi trường hợp, trang phải xử lý
onMessage
lệnh gọi lại, nhưng trong trường hợp ở nền sau, bạn cũng có thể cần xử lý
onBackgroundMessage
hoặc định cấu hình thông báo hiển thị để cho phép người dùng đưa
ứng dụng web của bạn vào nền trước.
| Trạng thái ứng dụng | Thông báo | Dữ liệu | Cả hai |
|---|---|---|---|
| Nền trước | onMessage |
onMessage |
onMessage |
| Nền sau (trình chạy dịch vụ) | onBackgroundMessage (thông báo hiển thị tự động xuất hiện) |
onBackgroundMessage |
onBackgroundMessage (thông báo hiển thị tự động xuất hiện) |
Mẫu hướng dẫn nhanh về JavaScript minh hoạ tất cả mã cần thiết để nhận thông báo.
Xử lý thông báo khi ứng dụng web của bạn ở nền trước
Để nhận sự kiện onMessage, ứng dụng của bạn phải xác định
trình chạy dịch vụ nhắn tin Firebase trong firebase-messaging-sw.js.
Ngoài ra, bạn có thể cung cấp trình chạy dịch vụ hiện có cho SDK thông qua
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();
Khi ứng dụng của bạn ở nền trước (người dùng đang xem trang web của bạn), bạn có thể nhận trực tiếp tải trọng dữ liệu và thông báo trong trang.
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); // ... });
Xử lý thông báo khi ứng dụng web của bạn ở nền sau
Tất cả thông báo nhận được khi ứng dụng ở nền sau đều kích hoạt thông báo hiển thị trong trình duyệt. Bạn có thể chỉ định các tuỳ chọn cho thông báo này, chẳng hạn như tiêu đề hoặc hành động khi nhấp, trong yêu cầu gửi từ máy chủ ứng dụng hoặc sử dụng logic trình chạy dịch vụ trên máy khách.
Đặt các tuỳ chọn thông báo trong yêu cầu gửi
Đối với các thông báo được gửi từ máy chủ ứng dụng, FCM
API JavaScript hỗ trợ
fcm_options.link
khoá. Thông thường, khoá này được đặt thành một trang trong ứng dụng web của bạn:
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"
}
}
}
}
Nếu giá trị đường liên kết trỏ đến một trang đã mở trong thẻ trình duyệt, thì việc nhấp vào thông báo sẽ đưa thẻ đó vào nền trước. Nếu trang chưa mở, thì việc nhấp vào thông báo sẽ mở trang đó trong một thẻ mới.
Vì thông báo dữ liệu không hỗ trợ fcm_options.link, nên bạn nên
thêm tải trọng thông báo vào tất cả thông báo dữ liệu. Ngoài ra, bạn có thể xử lý thông báo bằng trình chạy dịch vụ.
Để biết giải thích về sự khác biệt giữa thông báo và thông báo dữ liệu, hãy xem bài viết Các loại thông báo.
Đặt các tuỳ chọn thông báo trong trình chạy dịch vụ
Đối với thông báo dữ liệu, bạn có thể đặt các tuỳ chọn thông báo trong trình chạy dịch vụ. Trước tiên, hãy khởi chạy ứng dụng của bạn trong trình chạy dịch vụ:
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();
Để đặt các tuỳ chọn, hãy gọi onBackgroundMessage
trong firebase-messaging-sw.js.
Trong ví dụ này, chúng ta tạo một thông báo có các trường tiêu đề, nội dung và biểu tượng.
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); });
Các phương pháp hay nhất cho thông báo
Đối với những nhà phát triển gửi thông báo thông qua FCM cho Web, các yếu tố quan trọng nhất cần cân nhắc là độ chính xác và mức độ phù hợp. Dưới đây là một số đề xuất cụ thể để đảm bảo thông báo của bạn chính xác và phù hợp:
- Sử dụng trường biểu tượng để gửi một hình ảnh có ý nghĩa. Đối với nhiều trường hợp sử dụng, đây phải là biểu trưng của công ty hoặc ứng dụng mà người dùng nhận ra ngay lập tức. Hoặc đối với ứng dụng trò chuyện, đó có thể là ảnh hồ sơ của người dùng gửi.
- Sử dụng trường tiêu đề để thể hiện chính xác bản chất của thông báo. Ví dụ: "Jimmy đã trả lời" truyền tải thông tin chính xác hơn so với "Thông báo mới". Đừng sử dụng không gian có giá trị này cho tên công ty hoặc ứng dụng của bạn – hãy sử dụng biểu tượng cho mục đích đó.
- Đừng sử dụng tiêu đề hoặc nội dung thông báo để hiển thị tên hoặc miền trang web của bạn; thông báo đã chứa tên miền của bạn.
- Thêm
fcm_options.link, thường là để liên kết người dùng quay lại ứng dụng web của bạn và đưa ứng dụng đó vào tiêu điểm trong trình duyệt. Trong một số ít trường hợp mà tất cả thông tin bạn cần truyền tải có thể vừa với thông báo, bạn có thể không cần đường liên kết.