JavaScript
Push Notifications

Push Notifications for JavaScript

By using our Chat SDK for JavaScript, you can send notification messages to your hybrid mobile application users. Through those notification messages, users can receive important information when their devices are either running your client app in the background or idle. You can also show the content of notification messages locally from your app while it is in the foreground.

Note: The Chat SDK does not support push notifications in the web applications delivered through a variety of browsers, such as IE, Chrome, and so on. But our webhook service notifies you of the various events happening in your application if you want. With these events, you can build your own notification system. Currently, only a hybrid mobile application in JavaScript can handle push notifications with our Chat SDK.

Currently, the push notification functionality of the Chat SDK is only compatible with React Native among a variety of hybrid mobile application frameworks. This page explains how to enable push notifications in your React Native app by using Firebase Cloud Messaging (FCM) and the Chat SDK.

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

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

Note: Push notifications are supported in group channel only, and are not available in open channels.


Step 1: Install a react-native-firebase library and configure FCM and APNs

The react-native-firebase (RNFirebase) library is an easy-to-use FCM library for simple integration. You can configure FCM and APNs for your React Native project by following the instructions in the documentation. See the React Native Firebase Documentation's Notifications page.

Note: As GCM server and client APIs are deprecated and will be removed as of April 11, 2019, we recommend that you use FCM and develop push notifications with the react-native-firebase library for your project.


Step 2: Register tokens for FCM and APNs to 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 FCM registration token and APNs device token for the 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 Sendbird server, which are used to communicate with the FCM server. The following is an example of the registration in our React Native sample.

Light Color Skin
Copy
const sb = SendBird.getInstance();

if (Platform.OS === 'ios') {
    firebase.messaging().ios.getAPNSToken()
        .then(token => {
            sb.registerAPNSPushTokenForCurrentUser(token, function(response, error) {
                // Do something in response to a successful registeration.
            });
        })
        .catch(error => {
        });
} else {
    firebase.messaging().getToken()
        .then(token => {
            sb.registerGCMPushTokenForCurrentUser(token, function(response, error) {
                // Do something in response to a successful registeration.
            }); 
        })
        .catch(error => {
        });
}

Step 3: Receive FCM notification messages

Once the token is registered, you can make the client app instance to receive and handle FCM notification messages regardless of iOS and Android platforms. To learn more about the implementation, refer to the React Native Firebase Documentation's Usage page.

With the instructions of the Receiving Messages section, you can also find a way to receive FCM messages via the onMessage() listener, which monitors changes to the state (foreground/background, inactive) of your client app and helps you handle the FCM messages.

The sample code below shows how to parse received FCM messages by using the library's module.

Note: To display notifications in Android 8.0 (API level 26) and higher, you should provide a Notification instance with some required data, such as a channel ID.

Light Color Skin
Copy
const text = message.data.message;
const payload = JSON.parse(message.data.sendbird);
const localNotification = new firebase.notifications.Notification({
        show_in_foreground: true
    })
    .android.setChannelId(CHANNEL_ID)   // This is required for compatibility with Android 8.0 (API level 26) and higher
    .android.setSmallIcon(NOTIFICATION_ICON_RESOURCE_ID)
    .android.setPriority(firebase.notifications.Android.Priority.High)
    .setNotificationId(message.messageId)
    .setTitle('New message has arrived!')
    .setSubtitle('Number of unread messages: ${payload.unread_message_count}')
    .setBody(text)
    .setData(payload);

firebase.notifications().displayNotification(localNotification);

The data above, which is parsed from a FCM data message, contains a set of key-value items below in JSON format. It has the full set of information about the push notification. For example, the value of the message key means a received text message.

Light Color Skin
Copy
{
    "category": "messaging:offline_notification",
    "type": string,                 // Message type: 'User', 'File' or 'Admin'
    "message": string,              // User input message
    "data": string,                 // Custom data field
    "custom_type": string,          // Custom message type
    "message_id": long,             // Message ID
    "created_at": long,             // 13-digit timestamp
    "app_id": string,               // Application's unique ID
    "unread_message_count": int,    // Total unread count of the user
    "channel": {
        "channel_url": string,      // Group channel URL
        "name": string,             // Group channel name
        "custom_type": string       // Group channel custom_type
    },
    "channel_type": string,         // Channel type: 'messaging', 'group_messaging', or 'chat'
    "sender": {
        "id": string,               // Sender's unique ID
        "name": string,             // Sender's nickname
        "profile_url": string       // Sender's profile image URL 
    },
    "recipient": {
        "id": string,               // Recipient's unique ID
        "name": string              // Recipient's nickname
    },
    "files": [],                    // If a message is a file link, this array represents files
    "translations": {},             // If a message has translations, this dict has locale:translation.
    "push_alert": string,           // A customized alert push notification 
    "push_sound": string,           // The location of a sound file for notification messages
    "audience_type": string,        // The type of audiences to receive notification messages
    "mentioned_users": {
        "user_id": string,                        // The ID of a mentioned user
        "total_unread_mention_count": int,        // The number of messages which a user has been mentioned but has not read within the channels
        "channel_unread_mention_count": int,      // The number of channels with messages which a user has been mentioned but has not read
        "is_hidden": boolean                      // Whether or not a mentioned user has hidden the channel from the list
    }
}

Notification preferences

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

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

Light Color Skin
Copy
const sb = SendBird.getInstance();

setPushNotification(enbale, os) {
    if (enable) {
        if (os === 'ios') {
            sb.registerAPNSPushTokenForCurrentUser(TOKEN, function(response, error) {
                if (error) {
                    return;
                }
            
                // Do something in response to a successful registeration.
            });
        } else {
            sb.registerGCMPushTokenForCurrentUser(TOKEN, function(response, error) {
                if (error) {
                    return;
                }

                // Do something in response to a successful registeration.
            });
        }
    } else {
        if (os === 'ios') {
            sb.unregisterAPNSPushTokenForCurrentUser(TOKEN, function(response, error) {
                if (error) {
                    return;
                }
                
                // Do something in response to a successful unregisteration.
            });
        } else {
            sb.unregisterGCMPushTokenForCurrentUser(TOKEN, function(response, error) {
                if (error) {
                    return;
                }

                // Do something in response to a successful unregisteration.
            });
        }
    }
}             

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:

OptionDescription

all

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

mention_only

When disconnected from 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.

Light Color Skin
Copy
const sb = SendBird.getInstance();

// If you want to trigger notification messages only when the current user is mentioned in messages. 
sb.setPushTriggerOption('mention_only', function(response, error) {
    if (error) {
        return;
    }
});

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:

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 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 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.

Light Color Skin
Copy
// If you want to automatically apply the user's push notification setting to the channel.
groupChannel.setMyPushTriggerOption('default', function(response, error) {
    if (error) {
        return;
    }

    // If you want to turn off notification messages for this channel, pass `false` as an argument to a parameter. By default, they are turned on for a channel (true). 
    groupChannel.setPushPreference(false, function(response, error) {
        if (error) {
            return;
        }   
    });
    
    // Do something in response to setting 
});

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.

Light Color Skin
Copy
const sb = SendBird.getInstance();

// The current user will not receive push notifications during the specified time of every day.
sb.setDoNotDisturb(true, START_HOUR, START_MIN, END_HOUR, END_MIN, 'Asia/Seoul', function(response, error) {
    if (error) {
        return;
    }

    // Do something in response to setting 
});

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.

Light Color Skin
Copy
const sb = SendBird.getInstance();

// The current user will not receive notification messages during the specified period of time (from START_TS to END_TS).
sb.setSnoozePeriod(true, START_TS, END_TS, function(response, error) {
    if (error) {
        return;
    }

    // Do something in response to setting
});

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 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}, and {channel_name}, which represent the corresponding string values.

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

Text messageFile message

Default template

{sender_name}: {message} (ex. Cindy: Hi!)

{filename} (ex. 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 PUSH_TEMPLATE_DEFAULT or PUSH_TEMPLATE_ALTERNATIVE.

Light Color Skin
Copy
const sb = SendBird.getInstance();

sb.setPushTemplate(sb.PUSH_TEMPLATE_ALTERNATIVE, function(response, error) {
    if (error) {
        return;
    }

    // Push template successfully set to PUSH_TEMPLATE_ALTERNATIVE.
});

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

Light Color Skin
Copy
const sb = SendBird.getInstance();

sb.getPushTemplate(function(response, error) {
    if (error) {
        return;
    }
    
    if (response == sb.PUSH_TEMPLATE_DEFAULT)) {
        // Currently configured to use the default template.
    } else if (response == sb.PUSH_TEMPLATE_ALTERNATIVE)) {
        // Currently configured to use the alternative template.
    }
});

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:

Light Color Skin
Copy
const sb = SendBird.getInstance();
var preferredLanguages = ['fr', 'de', 'es', 'ko'];  // French, German, Spanish, and Korean

sb.updateCurrentUserInfoWithPreferredLanguages(preferredLanguages, function(error, user) {
    if (error) {
        return;
    }
    
    var isUpdatedSuccessfully = true;

    for (var language in sb.getCurrentUser().preferredLanguages) {   // The 'sb.getCurrentUser().preferredLanguages' returns a list of the current user's preferred languages.
        if (!preferredLanguages.inlcudes(language)) {
            isUpdatedSuccessfully = false;
            break;
        }
    }

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

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

Light Color Skin
Copy
{
    "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": "안녕하십니까?"
        },

        ...
    }
}