Ricevere messaggi nelle app web

Seleziona la piattaforma: iOS+ Android Web Flutter Unity C++


Il comportamento dei messaggi varia a seconda che la pagina sia in primo piano (abbia lo stato attivo) o in background, nascosta dietro altre schede o completamente chiusa. In tutti i casi, la pagina deve gestire il onMessage callback, ma nei casi in background potrebbe essere necessario gestire anche onBackgroundMessage o configurare la notifica di visualizzazione per consentire all'utente di portare la tua app web in primo piano.

Stato dell'app Notifica Dati Entrambe
Primo piano onMessage onMessage onMessage
Background (service worker) onBackgroundMessage (notifica di visualizzazione mostrata automaticamente) onBackgroundMessage onBackgroundMessage (notifica di visualizzazione mostrata automaticamente)

L'esempio di avvio rapido di JavaScript mostra tutto il codice necessario per ricevere i messaggi.

Gestire i messaggi quando l'app web è in primo piano

Per ricevere l'evento onMessage, la tua app deve definire il service worker di Firebase Messaging in firebase-messaging-sw.js. In alternativa, puoi fornire un service worker esistente all'SDK tramite getToken(): Promise<string>.

Web

import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging/sw";

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
const firebaseApp = initializeApp({
  apiKey: 'api-key',
  authDomain: 'project-id.firebaseapp.com',
  databaseURL: 'https://project-id.firebaseio.com',
  projectId: 'project-id',
  storageBucket: 'project-id.appspot.com',
  messagingSenderId: 'sender-id',
  appId: 'app-id',
  measurementId: 'G-measurement-id',
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = getMessaging(firebaseApp);

Web

// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here. Other Firebase libraries
// are not available in the service worker.
// Replace 10.13.2 with latest version of the Firebase JS SDK.
importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-messaging-compat.js');

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp({
  apiKey: 'api-key',
  authDomain: 'project-id.firebaseapp.com',
  databaseURL: 'https://project-id.firebaseio.com',
  projectId: 'project-id',
  storageBucket: 'project-id.appspot.com',
  messagingSenderId: 'sender-id',
  appId: 'app-id',
  measurementId: 'G-measurement-id',
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();

Quando l'app è in primo piano (l'utente sta visualizzando la tua pagina web ), puoi ricevere payload di dati e notifiche direttamente nella pagina.

Web

// Handle incoming messages. Called when:
// - a message is received while the app has focus
// - the user clicks on an app notification created by a service worker
//   `messaging.onBackgroundMessage` handler.
import { getMessaging, onMessage } from "firebase/messaging";

const messaging = getMessaging();
onMessage(messaging, (payload) => {
  console.log('Message received. ', payload);
  // ...
});

Web

// Handle incoming messages. Called when:
// - a message is received while the app has focus
// - the user clicks on an app notification created by a service worker
//   `messaging.onBackgroundMessage` handler.
messaging.onMessage((payload) => {
  console.log('Message received. ', payload);
  // ...
});

Gestire i messaggi quando l'app web è in background

Tutti i messaggi ricevuti mentre l'app è in background attivano una notifica di visualizzazione nel browser. Puoi specificare le opzioni per questa notifica, ad esempio il titolo o l'azione di clic, nella richiesta di invio dal server dell'app o utilizzando la logica del service worker sul client.

Impostare le opzioni di notifica nella richiesta di invio

Per i messaggi di notifica inviati dal server dell'app, l'FCM API JavaScript supporta la fcm_options.link chiave. In genere, questa chiave è impostata su una pagina dell'app web:

    https://fcm.googleapis.com/v1/projects/<YOUR-PROJECT-ID>/messages:send
    Content-Type: application/json
    Authorization: bearer <YOUR-ACCESS-TOKEN>

    {
      "message": {
        ,
        "notification": {
          "title": "Background Message Title",
          "body": "Background message body"
        },
        "webpush": {
          "fcm_options": {
            "link": "https://dummypage.com"
          }
        }
      }
    }

Se il valore del link rimanda a una pagina già aperta in una scheda del browser, facendo clic sulla notifica la scheda viene portata in primo piano. Se la pagina non è già aperta, un clic sulla notifica la apre in una nuova scheda.

Poiché i messaggi di dati non supportano fcm_options.link, ti consigliamo di aggiungere un payload di notifica a tutti i messaggi di dati. In alternativa, puoi gestire le notifiche utilizzando il service worker.

Per una spiegazione della differenza tra messaggi di notifica e messaggi di dati, consulta Tipi di messaggi.

Impostare le opzioni di notifica nel service worker

Per i messaggi di dati, puoi impostare le opzioni di notifica nel service worker. Innanzitutto, inizializza l'app nel service worker:

Web

import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging/sw";

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
const firebaseApp = initializeApp({
  apiKey: 'api-key',
  authDomain: 'project-id.firebaseapp.com',
  databaseURL: 'https://project-id.firebaseio.com',
  projectId: 'project-id',
  storageBucket: 'project-id.appspot.com',
  messagingSenderId: 'sender-id',
  appId: 'app-id',
  measurementId: 'G-measurement-id',
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = getMessaging(firebaseApp);

Web

// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here. Other Firebase libraries
// are not available in the service worker.
// Replace 10.13.2 with latest version of the Firebase JS SDK.
importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-messaging-compat.js');

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp({
  apiKey: 'api-key',
  authDomain: 'project-id.firebaseapp.com',
  databaseURL: 'https://project-id.firebaseio.com',
  projectId: 'project-id',
  storageBucket: 'project-id.appspot.com',
  messagingSenderId: 'sender-id',
  appId: 'app-id',
  measurementId: 'G-measurement-id',
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();

Per impostare le opzioni, chiama onBackgroundMessage in firebase-messaging-sw.js. In questo esempio, creiamo una notifica con i campi title, body e icon.

Web

import { getMessaging } from "firebase/messaging/sw";
import { onBackgroundMessage } from "firebase/messaging/sw";

const messaging = getMessaging();
onBackgroundMessage(messaging, (payload) => {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

  self.registration.showNotification(notificationTitle,
    notificationOptions);
});

Web

messaging.onBackgroundMessage((payload) => {
  console.log(
    '[firebase-messaging-sw.js] Received background message ',
    payload
  );
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

  self.registration.showNotification(notificationTitle, notificationOptions);
});

Best practice per le notifiche

Per gli sviluppatori che inviano notifiche tramite FCM per il web, le considerazioni più importanti sono la precisione e la pertinenza. Ecco alcuni consigli specifici per mantenere le notifiche precise e pertinenti:

  • Utilizza il campo icon per inviare un'immagine significativa. Per molti casi d'uso, questo dovrebbe essere il logo di un'azienda o di un'app che i tuoi utenti riconoscono immediatamente. In alternativa, per un'applicazione di chat, potrebbe essere l'immagine del profilo dell'utente che invia il messaggio.
  • Utilizza il campo title per esprimere la natura precisa del messaggio. Ad esempio, "Jimmy ha risposto" trasmette informazioni più precise rispetto a "Nuovo messaggio". Non utilizzare questo spazio prezioso per il nome della tua azienda o della tua app, ma utilizza l'icona a questo scopo.
  • Non utilizzare il titolo o il corpo della notifica per visualizzare il nome o il dominio del tuo sito web; le notifiche contengono già il nome di dominio.
  • Aggiungi fcm_options.link, in genere per reindirizzare l'utente alla tua app web e portare in primo piano nel browser. In rari casi in cui tutte le informazioni che devi trasmettere possono essere inserite nella notifica, potresti non aver bisogno di un link.