İletileri JavaScript istemcisinde alma

Mesajların davranışı, sayfanın ön planda (odaklanmış) veya arka planda, diğer sekmelerin arkasında gizlenmiş ya da tamamen kapalı olmasına bağlı olarak farklılık gösterir. Her durumda, sayfa onMessage geri çağırma işlemini gerçekleştirmelidir ancak arka plandaki durumlarda kullanıcının web uygulamanızı ön plana getirmesine izin vermek için onBackgroundMessage işlemini gerçekleştirmeniz veya görüntülü bildirimi yapılandırmanız gerekebilir.

Uygulama durumu Bildirim Veriler Her ikisi de
Ön plan onMessage onMessage onMessage
Arka plan (hizmet çalışanı) onBackgroundMessage (görüntüleme bildirimi otomatik olarak gösterilir) onBackgroundMessage onBackgroundMessage (görüntüleme bildirimi otomatik olarak gösterilir)

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

Web uygulamanız ön plandayken mesajları işleme

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

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.
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 plandayken (kullanıcı web sayfanızı görüntülerken) veri ve bildirim yüklerini doğrudan sayfadan alabilirsiniz.

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

Web uygulamanız arka plandayken mesajları işleme

Uygulama arka plandayken alınan tüm mesajlar, tarayıcıda bir görüntüleme bildirimi tetikler. Bu bildirimle ilgili seçenekleri (ör. başlık veya tıklama işlemi) uygulama sunucunuzdan gönderme isteğinde veya istemcide Service Worker mantığını kullanarak belirtebilirsiniz.

Gönderme isteğinde bildirim seçeneklerini ayarlama

Uygulama sunucusundan gönderilen bildirim mesajları için FCM JavaScript API, 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 sayfaya işaret ediyorsa bildirim tıklandığında bu sekme ön plana çıkar. Sayfa halihazırda açık değilse bildirim tıklandığında sayfa yeni bir sekmede açılır.

Veri mesajları fcm_options.link hizmetini desteklemediğinden tüm veri mesajlarına bir bildirim yükü eklemeniz önerilir. Alternatif olarak, bildirimleri Service Worker'ı kullanarak da işleyebilirsiniz.

Bildirim ve veri mesajları arasındaki farkın açıklaması için Mesaj türleri bölümüne bakın.

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

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.
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 içinde onBackgroundMessage numaralı telefonu arayın. Bu örnekte, başlık, gövde ve simge alanlarına sahip bir bildirim oluşturuyoruz.

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

Bildirimler için en iyi uygulamalar

Web için push mesajlaşma hakkında bilginiz varsa iyi bir bildirimin nasıl oluşturulacağıyla ilgili genel yönergeleri zaten okumuş olabilirsiniz. Web için FCM aracılığıyla bildirim gönderen geliştiricilerin en önemli hususları hassasiyet ve alaka düzeyidir. Aldığınız bildirimlerin eksiksiz ve alakalı olmasını sağlamanıza yönelik bazı özel önerileri aşağıda bulabilirsiniz:

  • Anlamlı bir resim göndermek için simge alanını kullanın. Birçok kullanım alanı için bu, kullanıcılarınızın hemen tanıyacağı bir şirket veya uygulama logosu olmalıdır. Bir sohbet uygulamasında, gönderen kullanıcının profil resmi de olabilir.
  • İletinin tam yapısını ifade etmek için başlık alanını kullanın. Örneğin, "Can yanıt verdi" ifadesi, "Yeni mesaj"a göre daha kesin bilgi verir. Bu değerli alanı şirketinizin veya uygulamanızın adı için kullanmayın. Simgeyi bu amaç için kullanın.
  • Web sitenizin adını veya alanınızı göstermek için bildirim başlığını ya da gövdesini kullanmayın. Bildirimlerde alan adınız zaten bulunur.
  • Genellikle kullanıcıyı web uygulamanıza tekrar bağlamak ve tarayıcıda ön plana çıkarmak için fcm_options.link ekleyin. Aktarmanız gereken tüm bilgilerin bildirime sığabileceği nadiren bir bağlantıya ihtiyacınız olmayabilir.