Send your First Message to a Backgrounded App

To get started with FCM, build out the simplest use case: sending a notification message to a specific user's device when the app is in the background on the device. This page lists all the steps to achieve this, from setup to verification — it may cover steps you already completed if you have set up a JavaScript client app for FCM.

Set up the SDK

If you haven't already, add Firebase to your JavaScript project.

Request permission to receive notifications

The method messaging.requestPermission() displays a consent dialog to let users grant your app permission to receive notifications in the browser. If permission is denied, FCM registration token requests result in an error.

messaging.requestPermission().then(function() {
  console.log('Notification permission granted.');
  // TODO(developer): Retrieve an Instance ID token for use with FCM.
  // ...
}).catch(function(err) {
  console.log('Unable to get permission to notify.', err);
});

Access the registration token

This section describes how to retrieve the registration token for an app instance, and how to monitor token refresh events. Because the token could be rotated after initial startup, you should monitor token refresh and always retrieve the latest updated registration token.

The registration token may change when:

  • The web app deletes the registration token.
  • The user clears browser data. In this case, call getToken to retrieve the new token.

Retrieve the current registration token

When you need to retrieve the current token, call getToken. This method returns null when permission has not been granted. Otherwise, it returns a token or rejects the promise due to an error.

The messaging service requires a firebase-messaging-sw.js file. Unless you already have a firebase-messaging-sw.js file, create an empty file with that name and place it in the root of your domain before retrieving a token. You can add meaningful content to the file later in the client setup process.

To retrieve the current token:

// Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken().then(function(currentToken) {
  if (currentToken) {
    sendTokenToServer(currentToken);
    updateUIForPushEnabled(currentToken);
  } else {
    // Show permission request.
    console.log('No Instance ID token available. Request permission to generate one.');
    // Show permission UI.
    updateUIForPushPermissionRequired();
    setTokenSentToServer(false);
  }
}).catch(function(err) {
  console.log('An error occurred while retrieving token. ', err);
  showToken('Error retrieving Instance ID token. ', err);
  setTokenSentToServer(false);
});

Monitor token refresh

The onTokenRefreshcallback fires whenever a new token is generated, so calling getToken in its context ensures that you are accessing a current, available registration token.

// Callback fired if Instance ID token is updated.
messaging.onTokenRefresh(function() {
  messaging.getToken().then(function(refreshedToken) {
    console.log('Token refreshed.');
    // Indicate that the new Instance ID token has not yet been sent to the
    // app server.
    setTokenSentToServer(false);
    // Send Instance ID token to app server.
    sendTokenToServer(refreshedToken);
    // ...
  }).catch(function(err) {
    console.log('Unable to retrieve refreshed token ', err);
    showToken('Unable to retrieve refreshed token ', err);
  });
});

After you've obtained the token, send it to your app server and store it using your preferred method. You can use the Instance ID server API to get information about subscriptions

Send a notification message

In the request body, set the token key in the message object to the registration token for the specific app instance you want to target. See the client setup information for your platform to learn more about registration tokens.

HTTP POST request

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA

{
  "message":{
    "token" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification" : {
      "body" : "This is an FCM notification message!",
      "title" : "FCM Message",
      }
   }
}

cURL

curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
"message":{
  "notification": {
    "title": "FCM Message",
    "body": "This is an FCM Message",
  },
  "token": "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
  }
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send

HTTP response

{
    "name": "projects/myproject-b5ae1/messages/0:1500415314455276%31bd1c9631bd1c96"
}

Add web push properties to a notification payload

With the HTTP v1 API you can specify additional notification options as a JSON object containing any valid properties from the Web Notification API. The title and body fields in this object, if present, override the equivalent google.firebase.fcm.v1.Notification.title and google.firebase.fcm.v1.Notification.body fields.

HTTP POST request

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...PbJ_uNasm

{
  "message": {
    "token" : <token of destination app>,
    "notification": {
      "title": "FCM Message",
      "body": "This is a message from FCM"
    },
    "webpush": {
      "headers": {
        "Urgency": "high"
      },
      "notification": {
        "body": "This is a message from FCM to web",
        "requireInteraction": "true",
        "badge": "/badge-icon.png"
      }
    }
  }
}

With this request, targeted web clients (including supported browsers running on Android) receive a high-priority notification message that remains active until the user interacts with it. It contains the fields:

  • Title: FCM Message
  • Body: This is a message from FCM to web
  • RequireInteraction: true
  • Badge: /badge-icon.png

Android and iOS native apps (to which the web overrides don't apply) receive a normal-priority notification message with:

  • Title: FCM Message
  • Body: This is a message from FCM

Note that RequireInteraction currently has only partial support among browsers. Developers should check the Web Notification API specification to verify platform and browser support.

cURL

curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...PbJ_uNasm" -H "Content-Type: application/json" -d '{
  "message": {
    "notification": {
      "title": "FCM Message",
      "body": "This is a message from FCM"
    },
    "webpush": {
      "headers": {
        "Urgency": "high"
      },
      "notification": {
        "body": "This is a message from FCM to web",
        "requireInteraction": "true",
        "badge": "/badge-icon.png"
      }
    }
  },
  "token": "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
  }
}' "https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send"

HTTP response

{
    "name": "projects/myproject-b5ae1/messages/0:1500415314455276%31bd1c9631bd1c98"
}

See Build App Server Send Requests to learn more about FCM messages.

Next steps

Send messages to foregrounded apps

Once you have successfully sent notification messages while your app is in the background, see Receive Messages in a JavaScript Client to get started sending to foregrounded apps.

Go beyond notification messages

To go beyond notification messages and add other, more advanced behavior to your app, see:

Gửi phản hồi về...

Bạn cần trợ giúp? Truy cập trang hỗ trợ của chúng tôi.