Gửi tin nhắn thử nghiệm cho một ứng dụng chạy trong nền
Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Để bắt đầu với FCM, hãy xây dựng trường hợp sử dụng đơn giản nhất: gửi thông báo cho một người dùng cụ thể khi ứng dụng ở chế độ nền trên thiết bị.
Trang này liệt kê tất cả các bước để đạt được mục tiêu này, từ thiết lập đến xác minh. Trang này có thể bao gồm những bước mà bạn đã hoàn tất nếu bạn đã thiết lập một ứng dụng JavaScript phía máy khách cho FCM.
Khi cần truy xuất mã thông báo đăng ký hiện tại cho một phiên bản ứng dụng, trước tiên, hãy yêu cầu người dùng cấp quyền nhận thông báo bằng Notification.requestPermission().
Khi được gọi như minh hoạ, phương thức này sẽ trả về một mã thông báo nếu được cấp quyền hoặc từ chối lời hứa nếu bị từ chối:
FCM yêu cầu tệp firebase-messaging-sw.js.
Trừ phi bạn đã có tệp firebase-messaging-sw.js, hãy tạo một tệp trống có tên đó và đặt tệp đó vào thư mục gốc của miền trước khi truy xuất mã thông báo.
Sau này, bạn có thể thêm nội dung có ý nghĩa vào tệp trong quá trình thiết lập ứng dụng.
Cách truy xuất mã thông báo hiện tại:
Web
import{getMessaging,getToken}from"firebase/messaging";// Get registration token. Initially this makes a network call, once retrieved// subsequent calls to getToken will return from cache.constmessaging=getMessaging();getToken(messaging,{vapidKey:'<YOUR_PUBLIC_VAPID_KEY_HERE>'}).then((currentToken)=>{if(currentToken){// Send the token to your server and update the UI if necessary// ...}else{// Show permission request UIconsole.log('No registration token available. Request permission to generate one.');// ...}}).catch((err)=>{console.log('An error occurred while retrieving token. ',err);// ...});
// Get registration token. Initially this makes a network call, once retrieved// subsequent calls to getToken will return from cache.messaging.getToken({vapidKey:'<YOUR_PUBLIC_VAPID_KEY_HERE>'}).then((currentToken)=>{if(currentToken){// Send the token to your server and update the UI if necessary// ...}else{// Show permission request UIconsole.log('No registration token available. Request permission to generate one.');// ...}}).catch((err)=>{console.log('An error occurred while retrieving token. ',err);// ...});
Nếu đây là thông báo đầu tiên của bạn, hãy chọn Tạo chiến dịch đầu tiên.
Chọn Thông báo của Firebase rồi chọn Tạo.
Nếu không, trên thẻ Chiến dịch, hãy chọn Chiến dịch mới rồi chọn Thông báo.
Nhập nội dung tin nhắn. Tất cả các trường khác đều không bắt buộc.
Chọn Gửi tin nhắn thử nghiệm trong ngăn bên phải.
Trong trường có nhãn Thêm mã thông báo đăng ký FCM, hãy nhập mã thông báo đăng ký mà bạn đã nhận được trong một phần trước đó của hướng dẫn này.
Chọn Kiểm tra.
Sau khi bạn chọn Kiểm thử, thiết bị khách hàng mục tiêu (có ứng dụng ở chế độ nền) sẽ nhận được thông báo.
Các bước tiếp theo
Gửi thông báo đến các ứng dụng ở nền trước
Sau khi bạn gửi thành công thông báo trong khi ứng dụng ở chế độ nền, hãy xem phần Nhận thông báo trong ứng dụng JavaScript để bắt đầu gửi đến các ứng dụng ở chế độ nền.
Không chỉ dừng lại ở thông báo
Để vượt ra ngoài thông báo và thêm các hành vi khác, nâng cao hơn vào ứng dụng của bạn, hãy xem:
[[["Dễ hiểu","easyToUnderstand","thumb-up"],["Giúp tôi giải quyết được vấn đề","solvedMyProblem","thumb-up"],["Khác","otherUp","thumb-up"]],[["Thiếu thông tin tôi cần","missingTheInformationINeed","thumb-down"],["Quá phức tạp/quá nhiều bước","tooComplicatedTooManySteps","thumb-down"],["Đã lỗi thời","outOfDate","thumb-down"],["Vấn đề về bản dịch","translationIssue","thumb-down"],["Vấn đề về mẫu/mã","samplesCodeIssue","thumb-down"],["Khác","otherDown","thumb-down"]],["Cập nhật lần gần đây nhất: 2025-09-05 UTC."],[],[],null,["To get started with FCM, build out the simplest use case: sending a\nnotification message to a specific user\nwhen the app is in the background on the device.\nThis page lists all the steps to achieve this, from setup to verification\n--- it may cover steps you already completed if you\nhave [set up a JavaScript client app](/docs/cloud-messaging/js/client)\nfor FCM.\n| **Important:** This guide focuses on the background case. If you want to receive messages when your app is in the foreground as well, see also [Receive Messages in a JavaScript Client](/docs/cloud-messaging/js/receive).\n\nSet up the SDK\n\nIf you haven't already, [add Firebase to your JavaScript project](/docs/web/setup).\n\nAccess the registration token\n\nWhen you need to retrieve the current registration token for an app instance, first\nrequest notification permissions from the user with `Notification.requestPermission()`.\nWhen called as shown, this returns a token if permission is granted or rejects the promise\nif denied:\n\n```javascript\nfunction requestPermission() {\n console.log('Requesting permission...');\n Notification.requestPermission().then((permission) =\u003e {\n if (permission === 'granted') {\n console.log('Notification permission granted.');\n```\n\n\u003cbr /\u003e\n\nFCM requires a `firebase-messaging-sw.js` file.\nUnless you already have a `firebase-messaging-sw.js` file, create an empty file\nwith that name and place it in the root of your domain before retrieving a token.\nYou can add meaningful content to the file later in the client setup process.\n\nTo retrieve the current token: \n\nWeb \n\n```javascript\nimport { getMessaging, getToken } from \"firebase/messaging\";\n\n// Get registration token. Initially this makes a network call, once retrieved\n// subsequent calls to getToken will return from cache.\nconst messaging = getMessaging();\ngetToken(messaging, { vapidKey: '\u003cYOUR_PUBLIC_VAPID_KEY_HERE\u003e' }).then((currentToken) =\u003e {\n if (currentToken) {\n // Send the token to your server and update the UI if necessary\n // ...\n } else {\n // Show permission request UI\n console.log('No registration token available. Request permission to generate one.');\n // ...\n }\n}).catch((err) =\u003e {\n console.log('An error occurred while retrieving token. ', err);\n // ...\n});https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/snippets/messaging-next/index/messaging_get_token.js#L8-L25\n```\n\nWeb \n\n```javascript\n// Get registration token. Initially this makes a network call, once retrieved\n// subsequent calls to getToken will return from cache.\nmessaging.getToken({ vapidKey: '\u003cYOUR_PUBLIC_VAPID_KEY_HERE\u003e' }).then((currentToken) =\u003e {\n if (currentToken) {\n // Send the token to your server and update the UI if necessary\n // ...\n } else {\n // Show permission request UI\n console.log('No registration token available. Request permission to generate one.');\n // ...\n }\n}).catch((err) =\u003e {\n console.log('An error occurred while retrieving token. ', err);\n // ...\n});https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/messaging/index.js#L27-L41\n```\n\nAfter you've obtained the token, send it to your app server and store\nit using your preferred method.\n\nSend a test notification message\n\n1. Install and run the app on the target device. On Apple devices, you'll need\n to accept the request for permission to receive remote notifications.\n\n2. Make sure the app is in the background on the device.\n\n3. In the Firebase console, open the [Messaging page](https://console.firebase.google.com/project/_/messaging/).\n\n4. If this is your first message, select **Create your first\n campaign**.\n\n 1. Select **Firebase Notification messages** and select **Create**.\n5. Otherwise, on the **Campaigns** tab, select **New campaign**\n and then **Notifications**.\n\n6. Enter the message text. All other fields are optional.\n\n7. Select **Send test message** from the right pane.\n\n8. In the field labeled **Add an FCM registration token**, enter the registration\n token you obtained in a previous section of this guide.\n\n9. Select **Test**.\n\nAfter you select **Test**, the targeted client device (with the app in\nthe background) should receive the notification.\n\nNext steps\n\nSend messages to foregrounded apps\n\nOnce you have successfully sent notification messages while your app is in\nthe background, see\n[Receive Messages in a JavaScript Client](/docs/cloud-messaging/js/receive)\nto get started sending to foregrounded apps.\n\nGo beyond notification messages\n\nTo go beyond notification messages and add other, more advanced behavior to your\napp, see:\n\n- [Receive Messages in a JavaScript Client](/docs/cloud-messaging/js/receive)\n- [Send Messages to Multiple Devices](/docs/cloud-messaging/js/send-multiple)"]]