Questa guida descrive come configurare Firebase Cloud Messaging nelle tue app client web e mobile in modo da poter ricevere messaggi in modo affidabile.
Il comportamento dei messaggi varia a seconda che la pagina sia in primo piano (in primo piano) o in background, nascosta dietro altre schede o completamente chiusa. In tutti i casi, la pagina deve gestire il callback
onMessage
, 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
web app in primo piano.
Stato dell'app | Notifica | Dati | Entrambe |
---|---|---|---|
Primo piano | onMessage |
onMessage |
onMessage |
Background (service worker) | onBackgroundMessage (notifica visualizzata automaticamente) |
onBackgroundMessage |
onBackgroundMessage (notifica visualizzata automaticamente) |
L'esempio di guida rapida 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 la tua app è in primo piano (l'utente sta visualizzando la tua pagina web), puoi ricevere dati e payload di 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, come il titolo o l'azione di clic, nella richiesta di invio dal server dell'app o utilizzando la logica del service worker sul client.
Imposta le opzioni di notifica nella richiesta di invio
Per i messaggi di notifica inviati dal server dell'app, l'API JavaScript supporta la chiave fcm_options.link
.FCM In genere, questa impostazione viene applicata a una pagina della tua 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, se fai 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, vedi 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 il numero onBackgroundMessage
in firebase-messaging-sw.js
.
In questo esempio, creiamo una notifica con i campi titolo, corpo e icona.
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 dell'icona per inviare un'immagine significativa. Per molti casi d'uso, questo deve essere un logo aziendale o dell'app che gli utenti riconoscono immediatamente. oppure, per un'applicazione di chat, potrebbe essere l'immagine del profilo dell'utente che invia il messaggio.
- Utilizza il campo del titolo 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. Utilizza l'icona a questo scopo.
- Non utilizzare il titolo o il corpo della notifica per visualizzare il nome del tuo sito web o il tuo dominio; le notifiche contengono già il nome del dominio.
- Aggiungi
fcm_options.link
, in genere per reindirizzare l'utente alla tua app web e portarla in primo piano nel browser. In rari casi in cui tutte le informazioni che devi comunicare possono essere inserite nella notifica, potresti non aver bisogno di un link.