Начните работу с Firebase Cloud Messaging в веб-приложениях.

Выберите платформу: iOS+ Android Web Flutter Unity C++


This guide describes how to get started with Firebase Cloud Messaging in your Web client apps so that you can reliably send messages.

The FCM JavaScript API lets you receive notification messages in web apps running in browsers that support the Push API . This includes the browser versions listed in this support matrix and Chrome extensions using the Push API.

The FCM SDK is supported only in pages served over HTTPS. This is due to its use of service workers, which are available only on HTTPS sites. If you need a provider, Firebase App Hosting is recommended and provides a no-cost tier for HTTPS hosting on your own domain.

To get started with the FCM JavaScript API, you'll need to add Firebase to your web app and add logic to access Firebase Installation IDs , which lets you designate the recipient for your notifications.

Добавьте и инициализируйте SDK FCM

  1. If you haven't already, install the Firebase JS SDK and initialize Firebase .

  2. Add the Firebase Cloud Messaging JS SDK and initialize Firebase Cloud Messaging :

Web

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-object
const firebaseConfig = {
  // ...
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);


// Initialize Firebase Cloud Messaging and get a reference to the service
const messaging = getMessaging(app);

Web

import firebase from "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-object
const firebaseConfig = {
  // ...
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);


// Initialize Firebase Cloud Messaging and get a reference to the service
const messaging = firebase.messaging();

Если вы используете FCM для веб-разработки и хотите обновить его до SDK 6.7.0 или более поздней версии, необходимо включить API регистрации FCM для вашего проекта в консоли Google Cloud . При включении API убедитесь, что вы вошли в консоль Google Cloud с той же учетной записью Google, которую используете для Firebase, и выберите правильный проект. В новых проектах, добавляющих SDK FCM , этот API включен по умолчанию.

Настройка учетных данных для веб-доступа с помощью FCM

The FCM Web interface uses Web credentials called Voluntary Application Server Identification, or VAPID keys, to authorize send requests to supported web push services. To subscribe your app to push notifications, you need to associate a pair of keys with your Firebase project. You can either generate a new key pair or import your existing key pair through the Firebase console.

Сгенерируйте новую пару ключей.

  1. В консоли Firebase перейдите по адресу Settings > General . Then, click the Cloud Messaging tab

  2. Перейдите в раздел «Веб-настройка» .

  3. На вкладке «Сертификаты Web Push» нажмите «Сгенерировать пару ключей» .

    В консоли отображается уведомление о том, что пара ключей была сгенерирована, а также строка открытого ключа и дата добавления.

Импортируйте существующую пару ключей.

Если у вас уже есть пара ключей, используемая в вашем веб-приложении, вы можете импортировать её в FCM , чтобы получить доступ к существующим экземплярам веб-приложения через API FCM . Для импорта ключей вам необходимы права доступа уровня владельца к проекту Firebase. Импортируйте существующий открытый и закрытый ключи в формате base64, закодированном в URL-адресе:

  1. В консоли Firebase перейдите по адресу Settings > General . Then, click the Cloud Messaging tab

  2. Перейдите в раздел «Веб-настройка» .

  3. In the Web Push certificates tab, find and select the link text: import an existing key pair .

  4. В диалоговом окне «Импорт пары ключей » укажите свой открытый и закрытый ключи в соответствующих полях и нажмите «Импорт» .

    В консоли отображается строка открытого ключа и дата добавления.

For instructions on how to add the key to your app, see Configure Web credentials in your app . For more information about the format of the keys and how to generate them, see Application server keys .

Настройте учетные данные для доступа к веб-ресурсам в вашем приложении.

The method register(): Promise<void> allows FCM to use the VAPID key credential when sending message requests to different push services. Using the key you generated or imported according to the instructions in Configure Web Credentials with FCM , add it in your code after the messaging object is retrieved:

import { getMessaging, register } from "firebase/messaging";

const messaging = getMessaging();
// Add the public key generated from the Firebase console here.
register(messaging, {vapidKey: "BKagOny0KF_2pCJQ3m....moL0ewzQ8rZu"});

Request notification permission and configure the service worker

When you need to target an app instance with FCM , first request notification permissions from the user with Notification.requestPermission() . When called as shown, this returns the permission state if granted:

function requestPermission() {
  console.log('Requesting permission...');
  Notification.requestPermission().then((permission) => {
    if (permission === 'granted') {
      console.log('Notification permission granted.');
    }
  });
}

FCM requires a firebase-messaging-sw.js file. Unless you already have a firebase-messaging-sw.js file, create an empty file with that name and place it in the root of your domain before registering. You can add meaningful content to the file later in the client setup process.

Получите доступ к идентификатору установки Firebase.

To register the app instance and retrieve the Firebase Installation ID (FID) for message targeting:

import { getMessaging, onRegistered, register } from "firebase/messaging";

const messaging = getMessaging();

// 1. Implement callback to receive the Firebase installation ID upon registration.
// This is triggered every time a manual register() finishes, a FID change
// is detected, or a pushsubscriptionchange event is fired.
onRegistered(messaging, (installationId) => {
  console.log('Registered installation ID:', installationId);

  // Send the Firebase Installation ID to your app server and update the UI if needed.
  sendRegistrationToServer(installationId);
});

// 2. You can also manually trigger registration (recommended on app startup)
register(messaging, {
  vapidKey: '<YOUR_PUBLIC_VAPID_KEY_HERE>'
}).then(() => {
  // Success! The Firebase Installation ID can be used to target messages to this app
  // instance and will be delivered asynchronously to your onRegistered() callback.
}).catch((err) => {
  console.error('An error occurred while registering', err);
});

The onRegistered callback is triggered in three scenarios:

  1. Каждый раз, когда завершается ручной вызов функции register() .
  2. Обнаружено изменение идентификатора установки Firebase.
  3. Срабатывает событие pushsubscriptionchange .

After you've obtained the Firebase Installation ID, send it to your app server and store it using your preferred method.

Воспользуйтесь регистрационным токеном (устаревшая функция).

Чтобы получить текущий токен:

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);
  // ...
});

After you've obtained the token, send it to your app server and store it using your preferred method.

Отправить тестовое уведомление

  1. Установите и запустите приложение на целевом устройстве. На устройствах Apple вам потребуется принять запрос на разрешение получения удаленных уведомлений.

  2. Убедитесь, что приложение запущено в фоновом режиме на устройстве.

  3. В консоли Firebase перейдите в раздел DevOps & Engagement > Messaging.

  4. Создайте кампанию.

    • Если это ваше первое сообщение:

      1. Выберите «Создать свою первую кампанию» .

      2. Выберите сообщения Firebase Notification и нажмите «Создать» .

    • Если вы ранее создавали кампании:

      1. На вкладке «Кампании» выберите «Новая кампания» .

      2. Нажмите «Уведомления» .

  5. Введите текст сообщения.

  6. В правой панели выберите пункт «Отправить тестовое сообщение» .

  7. В поле « Добавить регистрационный токен FCM введите свой регистрационный токен.

  8. Выберите тест .

После выбора пункта «Тест» целевое клиентское устройство, на котором приложение работает в фоновом режиме, должно получить уведомление.

Следующие шаги

After you have completed the setup steps, here are a few options for moving forward with FCM for Web (JavaScript):