Push API를 지원하는 브라우저에서 실행되는 웹 앱에서 FCM JavaScript API를 사용하여 알림 메시지를 수신할 수 있습니다.
여기에는 이 지원 매트릭스에 나열된 브라우저 버전과 Push API를 통한 Chrome 확장 프로그램이 포함됩니다.
FCM SDK는 HTTPS를 통해 제공되는 페이지에서만 지원됩니다. 이는 HTTPS 사이트에서만 사용 가능한 서비스 워커를 사용하기 때문입니다. 제공업체가 필요한 경우 자체 도메인에서 HTTPS 호스팅에 무료 등급을 제공하는 Firebase 호스팅을 사용하는 것이 좋습니다.
FCM JavaScript API를 시작하려면 웹 앱에 Firebase를 추가하고 등록 토큰에 액세스하는 로직을 추가해야 합니다.
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을 현재 사용 중이고 SDK 6.7.0 이상으로 업그레이드하려면 Google Cloud 콘솔에서 프로젝트에 대해 FCM Registration API를 사용 설정해야 합니다. API를 사용 설정할 때는 Firebase에 사용하는 것과 동일한 Google 계정을 사용하여 Cloud Console에 로그인하고, 올바른 프로젝트를 선택해야 합니다. FCM SDK를 추가하는 새 프로젝트에는 기본적으로 이 API가 사용 설정됩니다.
FCM에서 웹 사용자 인증 정보 구성
FCM 웹 인터페이스는 '자발적 애플리케이션 서버 ID' 또는 'VAPID' 키라고 하는
웹 사용자 인증 정보를 사용하여 지원되는 웹 푸시 서비스에 대한 보내기 요청을
승인합니다. 앱에서 푸시 알림을 구독하려면 키 쌍을 Firebase 프로젝트에 연결해야 합니다. Firebase Console을 통해 새 키 쌍을 생성하거나 기존 키 쌍을 가져올 수 있습니다.
새 키 쌍 생성
Firebase 콘솔 설정 창의 클라우드 메시징 탭을 열고 웹 구성 섹션으로 스크롤합니다.
웹 푸시 인증서 탭에서 키 쌍 생성을 클릭합니다. Console에 키 쌍이 생성되었다는 알림이 표시되고 공개 키 문자열과 추가된 날짜가 표시됩니다.
기존 키 쌍 가져오기
이미 웹 앱에서 사용 중인 기존 키 쌍이 있으면 FCM으로 이 키 쌍을 가져와서 FCM API를 통해 기존 웹 앱 인스턴스에 연결할 수 있습니다. 키를 가져오려면 Firebase 프로젝트에 액세스할 수 있는 소유자 수준의 권한이 있어야 합니다. 기존 공개 및 비공개 키를 base64 URL 보안 인코딩 양식으로 가져옵니다.
Firebase 콘솔 설정 창의 클라우드 메시징 탭을 열고 웹 구성 섹션으로 스크롤합니다.
웹 푸시 인증서 탭에서 링크 텍스트인 '기존 키 쌍 가져오기'를 찾아서 선택합니다.
키 쌍 가져오기 대화상자에서 해당 필드에 공개 및 비공개 키를 입력하고 가져오기를 클릭합니다. Console에 공개 키 문자열과 추가된 날짜가 표시됩니다.
import{getMessaging,getToken}from"firebase/messaging";constmessaging=getMessaging();// Add the public key generated from the console here.getToken(messaging,{vapidKey:"BKagOny0KF_2pCJQ3m....moL0ewzQ8rZu"});
등록 토큰 액세스
앱 인스턴스의 현재 등록 토큰을 가져와야 한다면 먼저 Notification.requestPermission()을 사용해 사용자에게 알림 권한을 요청합니다.
다음과 같이 호출했을 때 권한이 부여되면 토큰을 반환하고 거부되면 프로미스를 거부합니다.
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.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);// ...});
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-05(UTC)"],[],[],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."]]