向后台应用发送测试消息
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
如需开始学习如何使用 FCM,您可以构建一个最简单的使用场景:当应用在某位用户的设备后台运行时,向该用户发送一条通知消息。本页面列出了实现上述目标所需执行的步骤,包括从设置到验证的所有步骤。如果您已针对 FCM 设置了 JavaScript 客户端应用,您可能已经完成了本页面中的一些步骤。
设置 SDK
如果您尚未将 Firebase 添加到您的 JavaScript 项目,请先添加。
获取注册令牌
如果您需要检索应用实例的当前注册令牌,请先使用 Notification.requestPermission()
向用户请求通知权限。按如下所示进行调用时,如果已授予权限,此函数会返回令牌;或者,如果已拒绝权限,此函数会拒绝 promise:
function requestPermission() {
console.log('Requesting permission...');
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
FCM 需要 firebase-messaging-sw.js
文件。除非您已经有 firebase-messaging-sw.js
文件,否则请创建一个使用该名称的空文件,并在检索令牌之前将该文件放在您网域的根目录中。您可以在后面的客户端设置流程中向该文件添加有意义的内容。
如需检索当前令牌,请参考以下代码:
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.
const messaging = 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 UI
console.log('No registration token available. Request permission to generate one.');
// ...
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
// ...
});
Web
// 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 UI
console.log('No registration token available. Request permission to generate one.');
// ...
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
// ...
});
获取令牌后,将其发送到您的应用服务器,并使用您首选的方法进行存储。
发送测试通知消息
在目标设备上安装并运行该应用。在 Apple 设备上,您需要接受权限请求,才能收到远程通知。
确保应用在设备的后台中运行。
在 Firebase 控制台中,打开“Messaging”(消息传递)页面。
如果这是您的第一条消息,请选择制作首个宣传活动。
- 选择 Firebase 通知消息,然后选择创建。
否则,请在宣传活动标签页上选择新建宣传活动,然后选择通知。
输入消息内容。所有其他字段都是选填字段。
从右侧窗格中选择发送测试消息。
在标签为添加 FCM 注册令牌的字段中,输入您根据本指南的前一部分获得的注册令牌。
选择测试。
在您选择测试后,目标客户端设备(在后台中运行应用)应该会接收到通知。
后续步骤
向前台应用发送消息
向在后台运行的应用成功发送通知消息后,您可参阅在 JavaScript 客户端中接收消息,尝试向前台应用发送消息。
除通知消息之外的其他功能
如果除了通知消息之外,您还要向应用添加其他更高级的行为,请参阅以下内容:
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-16。
[null,null,["最后更新时间 (UTC):2025-08-16。"],[],[],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)"]]