İletileri JavaScript istemcisinde alma

İletilerin davranışı bağlı olarak sayfa ön planda (odaklanmış) veya arka planda, gizli olup olmadığına başka sekmelerin arkasında ya da tamamen kapalı olabilir. Her durumda, sayfa onMessage geri arama, ama arka planda bu konuda da onBackgroundMessage veya görüntülenen bildirimi, kullanıcının Search Console'u kullanarak web uygulamasını ön plana getirir.

Uygulama durumu Bildirim Veriler İkisi 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 bölgesindeki Firebase mesajlaşma hizmeti çalışanı. Alternatif olarak, şunun üzerinden SDK'ya mevcut bir hizmet çalışanı sağlayabilirsiniz: 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.
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ı şu anda web'inizi görüntülüyordur) sayfası) gelen uygulamalarınızın yanı sıra Yükler.

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 bir ekranı tetikler bildirimi görebilirsiniz. Bu bildirimle ilgili seçenekleri belirleyebilirsiniz: (ör. başlık veya tıklama işlemi) veya istemcide Service Worker mantığını kullanabilirsiniz.

Gönderme isteğinde bildirim seçeneklerini ayarlama

Uygulama sunucusundan gönderilen bildirim mesajları için FCM, JavaScript API, fcm_options.link tuşuna basın. 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, tarayıcı sekmesinde zaten açık olan bir sayfaya işaret ediyorsa bildirim tıklandığında o sekme ön plana çıkar. Sayfa halihazırda açık değilse, bir bildirim tıklandığında sayfa yeni bir sekmesinden yararlanın.

Veri mesajları fcm_options.link hizmetini desteklemediğinden şunu yapmanız önerilir: Tüm veri mesajlarına bildirim yükü ekleyin. Alternatif olarak, hizmet çalışanı aracılığıyla bildirim alır.

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

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 belirlemek için onBackgroundMessage numaralı telefonu arayın firebase-messaging-sw.js içinde. 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şması hakkında bilginiz varsa nasıl iyi bildirim yapıldığına ilişkin genel yönergeleri izleyin. E-posta gönderen web için FCM aracılığıyla bildirim gönderilmesi hassasiyet ve alaka düzeyidir. Veri feed'inizi korumanıza yardımcı olacak net ve alakalı bildirimleriniz:

  • Anlamlı bir resim göndermek için simge alanını kullanın. Birçok kullanım alanında kullanıcılarınızın hemen tanıyacağı bir şirket veya uygulama logosu olmalıdır. Veya için gönderen kullanıcının profil resmi olabilir.
  • İletinin tam yapısını ifade etmek için başlık alanını kullanın. Örneğin, "Cem yanıt verdi" "Yeni mesaj"dan daha kesin bilgi verir. Kullanma şirketiniz veya uygulamanızın adı için bu değerli alanı görüntüleyebilirsiniz. Simgeyi altındaki bu amaca hizmet eder.
  • Web sitenizin adını göstermek için bildirim başlığını veya gövdesini kullanmayın. alan; bildirimler zaten alan adınızı içeriyor.
  • fcm_options.link ekleyin. Bu genellikle kullanıcıyı web uygulamanıza tekrar bağlamak ve odaklanacak şekilde ayarlayabilirsiniz. İhtiyacınız olan tüm bilgilerin bildirime sığabileceğinden bir bağlantıya ihtiyacınız olmayabilir.