Receive Messages in a JavaScript Client

The behavior of messages differs depending on whether the page is in the foreground (has focus), or in the background, hidden behind other tabs, or completely closed. In all cases the page must handle the onMessage callback, but in background cases you may also need to handle setBackgroundMessageHandler or configure the display notification to allow the user to bring your web app into the foreground.

App state Notification Data Both
Foreground onMessage onMessage onMessage
Background (service worker) Notification displayed by SDK setBackgroundMessageHandler Notification displayed by SDK

The JavaScript quickstart sample demonstrates all code required to receive messages.

Handle messages when your web app is in the foreground

In order to receive the onMessage event, your app must define the Firebase messaging service worker in firebase-messaging-sw.js. Alternatively, you can specify an existing service worker with useServiceWorker.

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

// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
  'messagingSenderId': 'YOUR-SENDER-ID'
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();

When your app is in the foreground (the user is currently viewing your web page), you can receive data and notification payloads directly in the page.

// Handle incoming messages. Called when:
// - a message is received while the app has focus
// - the user clicks on an app notification created by a sevice worker
//   `messaging.setBackgroundMessageHandler` handler.
messaging.onMessage(function(payload) {
  console.log("Message received. ", payload);
  // ...
});

Handle messages when your web app is in the background

All messages received while the app is in the background trigger a display notification in the browser. You can specify options for this notification, such as title or click action, either in the send request from your app server, or using service worker logic on the client.

Setting notification options in the send request

For notification messages sent from the app server, the FCM JavaScript API supports the click_action key. Typically this is set to a page in your web app, so that when a user clicks on the notification, your app is brought to the foreground.

https://fcm.googleapis.com/fcm/send
Content-Type: application/json
Authorization: key=AIzaSyC...akjgSX0e4

{ "notification": {
    "title": "Background Message Title",
    "body": "Background message body",
    "click_action" : "https://dummypage.com"
  },

  "to" : "eEz-Q2sG8nQ:APA91bHJQRT0JJ..."

}

Because data messages don't support click_action, you are recommended to add a notification payload to all data messages. Alternatively, you can handle notifications using the service worker.

For an explanation of the difference between notification and data messages, see Message types.

Setting notification options in the service worker

For both notification messages and data messages, you can set notification options in the service worker. First, initialize your app in the service worker:

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

// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
  'messagingSenderId': 'YOUR-SENDER-ID'
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();

To set options, call setBackgroundMessageHandler in firebase-messaging-sw.js. In this example, we set options for title, body, icon, and click action.

messaging.setBackgroundMessageHandler(function(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'
  };

  return self.registration.showNotification(notificationTitle,
      notificationOptions);
});

Best practices for notifications

If you're familiar with push messaging for web, you may have already read the broad guidelines for what makes a good notification. For developers sending notifications through FCM for Web, the most important considerations are precision and relevance. Here are some specific recommendations for keeping your notifications precise and relevant:

  • Use the icon field to send a meaningful image. For many use cases, this should be a company or app logo that your users immediately recognize. Or, for a chat application, it might be the sending user's profile image.
  • Use the title field to express the precise nature of the message. For example, "Jimmy replied" conveys more precise information than "New message." Don't use this valuable space for your company or app name — use the icon for that purpose.
  • Don't use the notification title or body to display your website name or domain; notifications already contain your domain name.
  • Add a click_action, usually to link the user back to your web app and bring it into focus in the browser. In rare cases where all the information you need to convey can be fit into the notification, you might not need a click action.

Send feedback about...

Need help? Visit our support page.