Chat JavaScript v4
Chat JavaScript
Chat
JavaScript
Home
/
Chat
/
JavaScript
This is the new Docs for Chat SDK v4 beta for JavaScript. To see the previous Docs, click here.

Push notifications

Using our Chat SDK for JavaScript, you can send notifications to your hybrid mobile application users. These notifications are delivered to users while their devices are idle or while the app is running in the background. You can also show the content of the notifications to your app while it is in the foreground.

Currently, only a hybrid mobile application with a React Native framework can handle push notifications with our Chat SDK. This page explains how to enable push notifications in your React Native app by using Firebase Cloud Messaging (FCM), Apple Push Notification service (APNs), and the Chat SDK.

Note: The Chat SDK doesn't support push notifications in web applications delivered through browsers like Chrome and Edge. But you can build your own notification system by using our webhook service to receive notifications for various events happening in your application.

While the Chat SDKs for iOS and Android automatically detect the state of your application, the Chat SDK for JavaScript doesn't. Therefore when the state changes, you should explicitly call the setForegroundState() or setBackgroundState() method.

The following steps in this page are written with the assumption that you have already registered the certificates and credentials of FCM and APNs to the Sendbird server via your dashboard or by using the platform API's related actions.

Note: Push notifications are only supported in group channels.


Step 1: Install libraries and configure FCM and APNs

FCM

The @react-native-firebase/app library is an easy-to-use FCM library for simple integration. You can configure FCM for your React Native project by following the instructions in the Notifications page from the React Native Firebase documentation.

$ npm install @react-native-firebase/app @react-native-firebase/messaging

Note: As the Google Cloud Messaging (GCM) server and client APIs are deprecated and removed as of April 11, 2019, we recommend that you use FCM and develop push notifications with the @react-native-firebase/app library for your project.

APNs

To receive push notifications on iOS devices, you can integrate APNs by installing the @react-native-community/push-notification-ios library. For more details, see the Install section of the library's documentation.

$ npm install @react-native-community/push-notification-ios

Step 2: Register tokens for FCM and APNs to the Sendbird server

Note: A user can have up to 20 FCM registration tokens and 20 APNs device tokens each. The oldest token will be deleted before a new token is added for a user who already has 20 registration or device tokens. Only the 20 newest tokens will be maintained for users who already have more than 20 of each token type.

The FCM server requires an FCM registration token and an APNs device token for client app instances when targeting a particular device to send a push notification. The Chat SDK provides an interface to register and unregister two types of tokens to the Sendbird server. The tokens are used to communicate with the FCM server. The following is an example of the registration in our React Native sample.

import messaging from '@react-native-firebase/messaging';

if (Platform.OS === 'ios') {
    const token = await messaging().getAPNSToken();
    await sb.registerAPNSPushTokenForCurrentUser(token);
} else {
    const token = await messaging().getToken();
    await sb.registerFCMPushTokenForCurrentUser(token);
}

Step 3: Receive notification messages

Once the token is registered, Android client apps receive notification messages via FCM, and iOS client apps via APNs.

While APNs requires no further configuration in receiving these messages, FCM requires the client app instance to receive and handle FCM notification messages. Instructions on the Receiving Messages section show you how to receive FCM messages based on the state (foreground, background, or quit) of the client app.

The sample code below shows how to parse received FCM messages and display the messages using local notifications while the client app is in the background or quit state.

Note: To display notifications in Android 8.0 (API level 26) and higher, you should provide a Notification instance with the required data, such as a channel ID. To display local notifications in iOS 9.0 and lower, we recommend using Notifee.

import messaging from '@react-native-firebase/messaging';
import notifee, { AndroidImportance } from '@notifee/react-native';

// Link: https://rnfirebase.io/messaging/usage#background--quit-state-messages
messaging().setBackgroundMessageHandler(async (message) => {
    const isSendbirdNotification = Boolean(message.data.sendbird);
    if(!isSendbirdNotification) return;

    const text = message.data.message;
    const payload = JSON.parse(message.data.sendbird);

    // The following is required for compatibility with Android 8.0 (API level 26) and higher.
    // Link: https://notifee.app/react-native/reference/createchannel
    // Link: https://notifee.app/react-native/reference/androidchannel
    const channelId = await notifee.createChannel({
        id: 'NOTIFICATION_CHANNEL_ID',
        name: 'NOTIFICATION_CHANNEL_NAME',
        importance: AndroidImportance.HIGH
    });

    // Link: https://notifee.app/react-native/reference/displaynotification
    await notifee.displayNotification({
        id: message.messageId,
        title: 'New message has arrived!',
        subtitle: `Number of unread messages: ${payload.unread_message_count}`,
        body: payload.message,
        data: payload,
        // Link: https://notifee.app/react-native/reference/notificationandroid
        android: {
            channelId,
            smallIcon: NOTIFICATION_ICON_RESOURCE_ID,
            importance: AndroidImportance.HIGH,
        },
        // Link: https://notifee.app/react-native/reference/notificationios
        ios: {
            foregroundPresentationOptions: {
                alert: true,
                badge: true,
                sound: true,
            },
        },
    });
})

Additionally, the sample code below shows how to handle local notifications in Android and iOS. Refer to the event sections of the Notifee and push-notification-ios libraries to learn more.

import Notifee, { EventType } from '@notifee/react-native';
import PushNotificationIOS from '@react-native-community/push-notification-ios';

// Handle data from '@react-native-community/push-notification-ios'
const onNotificationIOS = (notification) => {
    const data = notification?.getData();
    if (data && data.userInteraction === 1 && Boolean(data.sendbird)) {
        // navigate to channel
        // const channelUrl = data.sendbird.channel.channel_url;
    }
}

// Handle data from '@notifee/react-native'
const onNotificationAndroid = async (event) => {
    if(event.type === EventType.PRESS && Boolean(event.detail.notification?.data?.sendbird)) {
        // navigate to channel
        // const channelUrl = event.detail.notification.data.sendbird.channel.channel_url;
    }
}

const App = () => {
    useEffect(() => {
        PushNotificationIOS.getInitialNotification().then(onNotificationIOS);
        PushNotificationIOS.addEventListener('localNotification', onNotificationIOS);
        const unsubscribe = Notifee.onForegroundEvent(onNotificationAndroid);
        return () => {
            PushNotificationIOS.removeEventListener('localNotification');
            unsubscribe();
        }
    },[])

    // ...
    // Your app
}

Notifee.onBackgroundEvent(onNotificationAndroid)

The data above, which is parsed from an FCM data message, contains a set of key-value items shown in the below JSON format. The data has a full set of information about the push notification. For example, the value of the message key means a received text message. As for the channel_unread_count, the attribute can be added into or removed from the payload in Settings > Application > Notifications on Sendbird Dashboard.

{
    "category": "messaging:offline_notification",
    "type": string,                 // Message type: MESG, FILE, or ADMM.
    "message": string,              // User input message.
    "custom_type": string,          // Custom message type.
    "message_id": long,             // Message ID.
    "created_at": long,             // The time that the message was created in a 13-digit, Unix milliseconds format.
    "app_id": string,               // Application's unique ID.
    "unread_message_count": int,    // Total number of new messages unread by the user.
    "channel": {
        "channel_url": string,      // Group channel URL.
        "name": string,             // Group channel name.
        "custom_type": string,       // Custom Group channel type.
        "channel_unread_count": int // Total number of unread new messages from the specific channel.
    },
    "channel_type": string,         // The value of channel_type is set by the system. The messaging indicates a distinct group channel while 'group_messaging' indicates a private group channel and chat indicates all other cases.
    "sender": {
        "id": string,               // Sender's unique ID.
        "name": string,             // Sender's nickname.
        "profile_url": string,       // Sender's profile image URL.
        "require_auth_for_profile_image": false,
        "metadata": {}
    },
    "recipient": {
        "id": string,               // Recipient's unique ID.
        "name": string              // Recipient's nickname.
    },
    "files": [],                    // An array of data regarding the file message, such as filename.
    "translations": {},             // The items of locale:translation.
    "push_title": string,           // Title of a notification message that can be customized in the Sendbird Dashboard with or without variables.
    "push_sound": string,           // The location of a sound file for notifications.
    "audience_type": string,        // The type of audiences for notifications.
    "mentioned_users": {
        "user_id": string,          // The ID of a mentioned user.
        "nickname": string,         // The nickname of a mentioned user.
        "profile_url": string,      // Mentioned user's profile image URL.
        "require_auth_for_profile_image": false
    },
}

Notification preferences

By registering or unregistering the current user's registration token to the Sendbird server as below, you can turn push notifications on or off in the user's app.

Note: The registration and unregistration methods in the code below should be called after a user has established a connection with the Sendbird server via the connect() method.

const setPushNotification = (enable: boolean, os: 'ios' | 'android') => {
    if (enable) {
        if (os === 'ios') {
            await sb.registerAPNSPushTokenForCurrentUser(TOKEN);
        } else {
            await sb.registerFCMPushTokenForCurrentUser(TOKEN);
        }
    } else {
        if (os === 'ios') {
            await sb.unregisterAPNSPushTokenForCurrentUser(TOKEN);
        } else {
            await sb.unregisterFCMPushTokenForCurrentUser(TOKEN);
        }
    }
}

Push trigger options allow users to configure when to receive notification messages as well as what type of messages will trigger notification messages. The following three options are provided:

List of push trigger options

OptionDescription

all

When disconnected from the Sendbird server, the current user receives notifications for all new messages including messages the user has been mentioned in.

mention_only

When disconnected from the Sendbird server, the current user only receives notifications for messages the user has been mentioned in.

off

The current user doesn't receive any notifications.

await sb.setPushTriggerOption('mention_only');

Push trigger options for channel also allow users to configure the trigger for notification messages as well as turn notifications on or off for each channel. The following four options are provided:

List of push trigger options for channel

OptionDescription

default

The current user’s push notification trigger settings are automatically applied to the channel. This is the default setting.

all

When disconnected from the Sendbird server, the current user receives notifications for all new messages in the channel including messages the user has been mentioned in.

mention_only

When disconnected from the Sendbird server, the current user only receives notifications for messages in the channel the user has been mentioned in.

off

The current user doesn't receive any notifications in the channel.

await groupChannel.setMyPushTriggerOption('default');

If you want to routinely turn off push notification on the current user's client app according to a specified schedule, use our Do Not Disturb feature like the following.

Note: Do Not Disturb can also be set for a user with our platform API's update push preferences action.

await sb.setDoNotDisturb(true, START_HOUR, START_MIN, END_HOUR, END_MIN, 'Asia/Seoul');

To snooze notification messages for a specific period of time, use our snooze feature like the following.

Note: snooze can also be set for a user with our platform API's update push preferences action.

await sb.setSnoozePeriod(true, START_TS, END_TS);

Push notification content templates

Push notification content templates are pre-formatted forms that can be customized to display your own push notification messages on a user’s device. Sendbird provides two types: Default and Alternative. Both templates can be customized from your dashboard by going to Settings > Application > Notifications > Push notification content templates.

Content templates

There are two types of push notification content template: Default and Alternative. Default template is a template that applies to users with the initial notification message setting. Alternative template is used when a user selects a different notification content template instead of the default template.

The content in the template is set at the application level while the selection of templates is determined by a user or through the Platform API.

Note: When a custom channel type has its own customized push notification content template, it takes precedence over the default or alternative templates.

Both templates can be customized using the variables of sender_name, filename, message, channel_name, and file_type_friendly which will be replaced with the corresponding string values. The file_type_friendly field indicates the type of the file sent, such as Audio, Image, and Video.


Refer to the following table for the usage of content templates:

Content templates use cases

Text messageFile message

Default template

{sender_name}: {message}
An example can be Cindy: Hi!.

{filename}
An example can be hello_world.jpg.`

Alternative template

New message arrived

New file arrived

To apply a template to push notifications, use the setPushTemplate() method. Specify the template name as either with PushTemplate.DEFAULT or PushTemplate.ALTERNATIVE.

await sb.setPushTemplate(PushTemplate.ALTERNATIVE);

To check the current user's push notification template, use the getPushTemplate() method like the following:

const pushTemplate: PushTemplate = await sb.getPushTemplate();

Push notification translation

Push notification translation allows your users to receive notification messages in their preferred languages. Users can set up to four preferred languages. If messages are sent in one of those languages, the notification messages won’t be translated. If messages are sent in a language other than the preferred languages, the notification messages will be translated into the user's first preferred language. In addition, the messages translated into other preferred languages will be provided in the sendbird property of a notification message payload.

Note: A specific user's preferred languages can be set with our platform API's update a user action.

The current user's preferred languages can be set using the updateCurrentUserInfoWithPreferredLanguages() method as follows:

const preferredLanguages = ['fr', 'de', 'es', 'ko'];    // French, German, Spanish, and Korean.

try {
    let isUpdatedSuccessfully = true;
    for (let language of sb.currentUser.preferredLanguages) {   // The sb.currentUser.preferredLanguages returns a list of the current user's preferred languages.
        if (!preferredLanguages.includes(language)) {
            isUpdatedSuccessfully = false;
            break;
        }
    }

    if (isUpdatedSuccessfully) {
        // The current user's preferred languages have been updated successfully.
    }
} catch (error) {
    // Handle error.
}

If successful, the following notification message payload will be delivered to the current user's device.

{
    "message": {
        "token": "ad3nNwPe3H0:ZI3k_HHwgRpoDKCIZvvRMExUdFQ3P1...",
        "notification": {
            "title": "Greeting!",
            "body": "Bonjour comment allez vous"    // A notification message is translated into the first language listed in the preferred languages.
        }
    },
    "sendbird": {
        "category": "messaging:offline_notification",
        "type": "User",
        "message": "Hello, how are you?",
        ...

        "translations": {   // The translated messages in other preferred languages.
            "fr": "Bonjour comment allez vous",
            "de": "Hallo wie geht es dir",
            "es": "Hola como estas",
            "kr": "안녕하십니까?"
        },

        ...
    }
}