JavaScript istemcisinde mesaj alın

İletilerin davranışı, sayfanın ön planda (odaklanmış) veya arka planda, diğer sekmelerin arkasına gizlenmiş 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, kullanıcının web uygulamanızı ön plana getirmesine izin vermek için onBackgroundMessage da işlemeniz veya ekran bildirimini yapılandırmanız gerekebilir.

Uygulama durumu Bildiri Veri İkisi birden
ön plan onMessage onMessage onMessage
Arka plan (servis çalışanı) onBackgroundMessage (ekran bildirimi otomatik olarak gösterilir) onBackgroundMessage onBackgroundMessage (ekran 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 planda olduğunda iletileri işleyin

onMessage olayını 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> aracılığıyla SDK'ya mevcut bir hizmet çalışanı 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 plandayken (kullanıcı şu anda web sayfanızı görüntülüyor), 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 planda olduğunda mesajları işleyin

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 sunucunuzdaki gönderme isteğinde veya istemcide 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, 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, bildirimin tıklanması o sekmeyi ön plana getirir. Sayfa zaten açık değilse, bir bildirim tıklaması sayfayı yeni bir sekmede açar.

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

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 servis ç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 öğesini 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 push mesajlaşmaya aşina iseniz, iyi bir bildirimi neyin iyi yaptığına ilişkin kapsamlı yönergeleri zaten okumuş olabilirsiniz. Web için FCM aracılığıyla bildirim gönderen geliştiriciler için en önemli hususlar kesinlik ve alaka düzeyidir. Aşağıda, bildirimlerinizi kesin ve alakalı tutmak için bazı özel öneriler verilmiştir:

  • Anlamlı bir görüntü göndermek için simge alanını kullanın. Birçok kullanım durumu için bu, kullanıcılarınızın hemen tanıdığı bir şirket veya uygulama logosu olmalıdır. Veya bir sohbet uygulaması için gönderen kullanıcının profil resmi olabilir.
  • Mesajın doğasını tam olarak ifade etmek için başlık alanını kullanın. Örneğin, "Jimmy yanıtladı", "Yeni mesaj"dan daha kesin bilgiler aktarır. 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 etki alanını görüntülemek için bildirim başlığını veya gövdesini kullanmayın; bildirimler zaten alan adınızı içeriyor.
  • Genellikle kullanıcıyı tekrar web uygulamanıza bağlamak ve tarayıcıda odak noktasına getirmek için fcm_options.link ekleyin. İletmeniz gereken tüm bilgilerin bildirime sığabileceği nadir durumlarda, bir bağlantıya ihtiyacınız olmayabilir.