傳送測試訊息至背景執行的應用程式
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
如要開始使用 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 控制台中,開啟「訊息」頁面。
如果這是您的第一則訊息,請選取「建立您的第一個廣告活動」。
- 選取「Firebase 通知訊息」,然後選取「建立」。
否則,請在「廣告活動」分頁中選取「新增廣告活動」,然後選取「通知」。
輸入訊息文字。其他欄位則為選填。
在右側窗格中選取「傳送測試訊息」。
在標示為「新增 FCM 註冊權杖」的欄位中,輸入您在本指南先前章節中取得的註冊權杖。
選取「測試」。
選取「測試」後,目標用戶端裝置 (應用程式在背景執行) 應會收到通知。
後續步驟
將訊息傳送至前景應用程式
應用程式在背景執行時,成功傳送通知訊息後,請參閱「在 JavaScript 用戶端接收訊息」,開始傳送至前景應用程式。
不只是通知訊息
如要進一步瞭解通知訊息,並在應用程式中新增其他進階行為,請參閱:
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-16 (世界標準時間)。
[null,null,["上次更新時間: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)"]]