import{initializeApp}from"firebase/app";import{getMessaging}from"firebase/messaging";// TODO: Replace the following with your app's Firebase project configuration// See: https://firebase.google.com/docs/web/learn-more#config-objectconstfirebaseConfig={// ...};// Initialize Firebaseconstapp=initializeApp(firebaseConfig);// Initialize Firebase Cloud Messaging and get a reference to the serviceconstmessaging=getMessaging(app);
Web
importfirebasefrom"firebase/compat/app";import"firebase/compat/messaging";// TODO: Replace the following with your app's Firebase project configuration// See: https://firebase.google.com/docs/web/learn-more#config-objectconstfirebaseConfig={// ...};// Initialize Firebasefirebase.initializeApp(firebaseConfig);// Initialize Firebase Cloud Messaging and get a reference to the serviceconstmessaging=firebase.messaging();
如果您目前使用網頁版 FCM,並想升級至 6.7.0 以上版本的 SDK,請務必在 Google Cloud 控制台中為專案啟用 FCM 註冊 API。啟用 API 時,請務必使用 Firebase 專用的 Google 帳戶登入 Cloud 控制台,並選取正確的專案。新增 FCM SDK 的新專案預設會啟用這項 API。
import{getMessaging,getToken}from"firebase/messaging";constmessaging=getMessaging();// Add the public key generated from the console here.getToken(messaging,{vapidKey:"BKagOny0KF_2pCJQ3m....moL0ewzQ8rZu"});
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);// ...});
[null,null,["上次更新時間:2025-08-16 (世界標準時間)。"],[],[],null,["The FCM JavaScript API lets you receive notification messages in\nweb apps running in browsers that support the\n[Push API](https://www.w3.org/TR/push-api/).\nThis includes the browser versions listed in this\n[support matrix](https://caniuse.com/#feat=push-api) and Chrome extensions\nvia the Push API.\n\nThe FCM SDK is supported only in pages served over HTTPS. This is\ndue to its use of service workers, which are available only on HTTPS sites. If\nyou need a provider, [Firebase Hosting](/docs/hosting/quickstart) is\nrecommended and provides a no-cost tier for HTTPS hosting on your own domain.\n\nTo get started with the FCM JavaScript API, you'll need to add\nFirebase to your web app and add logic to access registration tokens.\n\nAdd and initialize the FCM SDK\n\n1. If you haven't already, [install the Firebase JS SDK and initialize Firebase](/docs/web/setup#add-sdk-and-initialize).\n\n2. Add the Firebase Cloud Messaging JS SDK and initialize Firebase Cloud Messaging:\n\nWeb\n\n\n| [Learn more](/docs/web/learn-more#modular-version) about the tree-shakeable modular web API and [upgrade](/docs/web/modular-upgrade) from the namespaced API.\n\n\u003cbr /\u003e\n\n```javascript\nimport { initializeApp } from \"firebase/app\";\nimport { getMessaging } from \"firebase/messaging\";\n\n// TODO: Replace the following with your app's Firebase project configuration\n// See: https://firebase.google.com/docs/web/learn-more#config-object\nconst firebaseConfig = {\n // ...\n};\n\n// Initialize Firebase\nconst app = initializeApp(firebaseConfig);\n\n\n// Initialize Firebase Cloud Messaging and get a reference to the service\nconst messaging = getMessaging(app);\n```\n\nWeb\n\n\n| [Learn more](/docs/web/learn-more#modular-version) about the tree-shakeable modular web API and [upgrade](/docs/web/modular-upgrade) from the namespaced API.\n\n\u003cbr /\u003e\n\n```javascript\nimport firebase from \"firebase/compat/app\";\nimport \"firebase/compat/messaging\";\n\n// TODO: Replace the following with your app's Firebase project configuration\n// See: https://firebase.google.com/docs/web/learn-more#config-object\nconst firebaseConfig = {\n // ...\n};\n\n// Initialize Firebase\nfirebase.initializeApp(firebaseConfig);\n\n\n// Initialize Firebase Cloud Messaging and get a reference to the service\nconst messaging = firebase.messaging();\n```\n\nIf you are currently using FCM for web and want to upgrade to SDK\n6.7.0 or later, you must enable the\n[FCM Registration API](//console.cloud.google.com/apis/library/fcmregistrations.googleapis.com)\nfor your project in the Google Cloud Console. When you enable the API,make sure\nyou are logged in to Cloud Console with the same Google account you use for\nFirebase, and make sure to select the correct project. New projects adding the\nFCM SDK have this API enabled by default.\n\nConfigure Web Credentials with FCM\n\nThe FCM Web interface uses Web credentials called \"Voluntary\nApplication Server Identification,\" or \"VAPID\" keys, to authorize send requests\nto supported web push services. To subscribe your app to push notifications, you\nneed to associate a pair of keys with your Firebase project. You can either\ngenerate a new key pair or import your existing key pair through the Firebase\nConsole.\n\nGenerate a new key pair\n\n1. Open the [Cloud Messaging](//console.firebase.google.com/project/_/settings/cloudmessaging/) tab of the Firebase console **Settings** pane and scroll to the **Web configuration** section.\n2. In the **Web Push certificates** tab, click **Generate Key Pair**. The console displays a notice that the key pair was generated, and displays the public key string and date added.\n\nImport an existing key pair\n\nIf you have an existing key pair you are already using with your web app, you\ncan import it to FCM so that you can reach your existing web app\ninstances through FCM APIs. To import keys, you must have\nowner-level access to the Firebase project. Import your existing public and\nprivate key in base64 URL safe encoded form:\n\n1. Open the [Cloud Messaging](//console.firebase.google.com/project/_/settings/cloudmessaging/) tab of the Firebase console **Settings** pane and scroll to the **Web configuration** section.\n2. In the **Web Push certificates** tab, find and select the link text, \"import an existing key pair.\"\n3. In the **Import a key pair** dialog, provide your public and private keys in the corresponding fields and click **Import**. The console displays the public key string and date added.\n\nFor instructions on how to add the key to your app, see\n[Configure Web credentials in your app](/docs/cloud-messaging/js/client#configure_web_credentials_in_your_app).\nFor more information about the format of the keys and how to generate them,\nsee [Application server keys](https://developers.google.com/web/fundamentals/push-notifications/web-push-protocol#application_server_keys).\n\nConfigure Web credentials in your app\n\nThe method [`getToken(): Promise\u003cstring\u003e`](/docs/reference/js/messaging_#gettoken)\nallows FCM to use the VAPID key credential when sending message\nrequests to different push services. Using the key you generated or imported\naccording to the instructions in\n[Configure Web Credentials with FCM](/docs/cloud-messaging/js/client#configure_web_credentials_with_fcm),\nadd it in your code after the messaging object is retrieved: \n\n import { getMessaging, getToken } from \"firebase/messaging\";\n\n const messaging = getMessaging();\n // Add the public key generated from the console here.\n getToken(messaging, {vapidKey: \"BKagOny0KF_2pCJQ3m....moL0ewzQ8rZu\"});\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\nNext steps\n\nAfter you have completed the setup steps, here are few options for moving\nforward with FCM for Web (JavaScript):\n\n- Add functionality to your app to [receive messages](/docs/cloud-messaging/js/receive).\n- Try one of our tutorials: [Send Your First Message to a Backgrounded App](/docs/cloud-messaging/js/first-message) or [Send Messages to Multiple Devices](/docs/cloud-messaging/js/send-multiple).\n- Review a complete [sample on GitHub](https://github.com/firebase/quickstart-js/tree/master/messaging).\n- Review the [JavaScript reference](/docs/reference/js/messaging_).\n- View a [video walkthrough](https://youtu.be/BsCBCudx58g) of implementing the API."]]