バックグラウンド アプリにテスト メッセージを送信する
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
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 Notification メッセージ] を選択し、[作成] を選択します。
それ以外の場合は、[キャンペーン] タブで [新しいキャンペーンを作成]、[通知] の順に選択します。
通知テキストを入力します。それ以外のフィールドはすべて省略可能です。
右側のペインで [テスト メッセージを送信] を選択します。
[FCM 登録トークンを追加] というラベルの付いたフィールドで、このガイドの前のセクションで取得した登録トークンを入力します。
[テスト] を選択します。
[テスト] を選択すると、アプリをバックグラウンドで実行しているターゲット クライアント デバイスに通知が届きます。
次のステップ
フォアグラウンドで動作しているアプリへのメッセージの送信
バックグラウンドで動作しているアプリに通知メッセージが正常に送信されたら、JavaScript クライアントでメッセージを受信するを参照して、フォアグラウンドで動作しているアプリへのメッセージの送信を試します。
通知メッセージ以外の動作
通知メッセージだけでなく、他のより高度な動作をアプリに追加する場合は、以下をご確認ください。
特に記載のない限り、このページのコンテンツはクリエイティブ・コモンズの表示 4.0 ライセンスにより使用許諾されます。コードサンプルは Apache 2.0 ライセンスにより使用許諾されます。詳しくは、Google Developers サイトのポリシーをご覧ください。Java は Oracle および関連会社の登録商標です。
最終更新日 2025-08-16 UTC。
[null,null,["最終更新日 2025-08-16 UTC。"],[],[],null,["# Send a test message to a backgrounded app\n\nTo 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--------------\n\nIf you haven't already, [add Firebase to your JavaScript project](/docs/web/setup).\n\nAccess the registration token\n-----------------------------\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\n### Web\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\n### Web\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--------------------------------\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----------\n\n### Send 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\n### Go 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)"]]