Bir JavaScript istemcisinde ileti alma

Mesajların davranışı, sayfanın ön planda (odak noktasının olması), arka planda olmasına, diğer sekmelerin arkasına gizlenmiş olmasına veya tamamen kapalı olmasına bağlı olarak farklılık gösterir. Her durumda sayfanın onMessage geri aramasını işlemesi gerekir, ancak arka planda onBackgroundMessage da işlemeniz veya kullanıcının web uygulamanızı ön plana getirmesine izin vermek için ekran bildirimini yapılandırmanız gerekebilir.

Uygulama durumu Bildiri Veri İkisi birden
Ön plan onMessage onMessage onMessage
Arka plan (hizmet çalışanı) onBackgroundMessage (görüntü bildirimi otomatik olarak gösterilir) onBackgroundMessage onBackgroundMessage (görüntü bildirimi otomatik olarak gösterilir)

JavaScript hızlı başlangıç ​​örneği, ileti almak için gereken tüm kodları gösterir.

Web uygulamanız ön plandayken mesajları yönetin

onMessage etkinliğini alabilmek için uygulamanızın firebase-messaging-sw.js dosyasında Firebase mesajlaşma hizmeti çalışanını tanımlaması gerekir. Alternatif olarak, getToken(): Promise<string> aracılığıyla SDK'ya mevcut bir hizmet çalışanını sağlayabilirsiniz.

Web modular API

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 namespaced API

// 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.
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.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();

Uygulamanız ön planda olduğunda (kullanıcı şu anda web sayfanızı görüntülüyorsa), verileri ve bildirim yüklerini doğrudan sayfada alabilirsiniz.

Web modular API

// 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 namespaced API

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

Web uygulamanız arka plandayken mesajları yönetin

Uygulama arka plandayken alınan tüm mesajlar, tarayıcıda bir ekran bildirimini tetikler. Bu bildirim için başlık veya tıklama eylemi gibi seçenekleri uygulama sunucunuzdan gönderme isteğinde veya istemcideki hizmet çalışanı mantığını kullanarak belirtebilirsiniz.

Gönderme isteğinde bildirim seçeneklerini ayarlama

Uygulama sunucusundan gönderilen bildirim mesajları için FCM JavaScript API'si fcm_options.link anahtarını destekler. Genellikle bu, web uygulamanızdaki bir sayfaya ayarlanır:

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

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

Bağlantı değeri, bir tarayıcı sekmesinde zaten açık olan bir sayfayı işaret ediyorsa, bildirime tıklandığında o sekme ön plana çıkar. Sayfa zaten açık değilse, bildirim tıklaması sayfayı yeni bir sekmede açar.

Veri mesajları fcm_options.link öğesini desteklemediğinden, tüm veri mesajlarına bir bildirim verisi eklemeniz önerilir. Alternatif olarak, hizmet çalışanını kullanarak bildirimleri yönetebilirsiniz.

Bildirim ve veri mesajları arasındaki farkın açıklaması için bkz. Mesaj türleri .

Hizmet çalışanında bildirim seçeneklerini ayarlama

Veri mesajları için hizmet çalışanında bildirim seçeneklerini ayarlayabilirsiniz. Öncelikle uygulamanızı hizmet çalışanında başlatın:

Web modular API

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 namespaced API

// 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.
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.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();

Seçenekleri ayarlamak için firebase-messaging-sw.js onBackgroundMessage arayın. Bu örnekte başlık, gövde ve simge alanlarıyla bir bildirim oluşturuyoruz.

Web modular API

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 namespaced API

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

Bildirimler için en iyi uygulamalar

Web için anlık mesajlaşma konusunda bilginiz varsa, iyi bir bildirimin ne olduğuna ilişkin genel yönergeleri zaten okumuş olabilirsiniz. FCM for Web aracılığıyla bildirim gönderen geliştiriciler için en önemli husus kesinlik ve uygunluktur. Bildirimlerinizi kesin ve alakalı tutmaya yönelik bazı özel öneriler şunlardır:

  • Anlamlı bir resim göndermek için simge alanını kullanın. Birçok kullanım durumunda bu, kullanıcılarınızın hemen tanıyacağı bir şirket veya uygulama logosu olmalıdır. Veya bir sohbet uygulaması için gönderen kullanıcının profil resmi olabilir.
  • İletinin kesin doğasını ifade etmek için başlık alanını kullanın. Örneğin, "Jimmy yanıtladı" ifadesi, "Yeni mesaj" ifadesinden daha kesin bilgi aktarır. Bu değerli alanı şirketiniz veya uygulama adınız için kullanmayın; simgeyi bu amaçla kullanın.
  • Web sitenizin adını veya alan adını görüntülemek için bildirim başlığını veya metnini kullanmayın; bildirimler zaten alan adınızı içeriyor.
  • Genellikle kullanıcıyı web uygulamanıza geri bağlamak ve onu tarayıcıda odak noktasına getirmek için fcm_options.link ekleyin. Aktarmanız gereken tüm bilgilerin bildirime sığabildiği nadir durumlarda, bir bağlantıya ihtiyacınız olmayabilir.