Push Notifications for JavaScript

Using our JavaScript SDK, you can send push notifications to users of your hybrid mobile application. Through those push notifications, users can receive important information even when your application is in the background on the user's device. You can also generate push notifications locally from your application while it is in the foreground.

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

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

Note: Push notifications are supported in Group Channel only. The SDK does not provide an option for users to receive push notifications from open channels.

Currently, the push notification functionality of the JavaScript SDK is only compatible with React Native among a variety of hybrid mobile application frameworks. The following describes how to enable push notifications in a React Native application using Firebase Cloud Messaging (FCM) and JavaScript SDK.

The following 3 steps are needed to send push notifications to users of your React Native application.

  1. Install a react-native-fcm library and configure FCM and APNs for your project. You can use any other FCM library in your own setup.
  2. Register APNs device token or FCM registration token for the client app instances to SendBird server.
  3. Send and receive a push notification.

Step 1: Install a react-native-fcm library and configure FCM and APNs for your project

We've searched for a useful library that enables users of our JavaScript SDK to send push notifications using FCM, and found an easy-to-use react-native-fcm library. 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-fcm library for your project.
In the react-native-fcm GitHub project page, you can find guides for: Installation, Configure Firebase console, Android configuration, iOS configuration, and Setup local notifications.


Step 2: Register APNs device token and FCM registration token of users to SendBird server

The FCM server requires APNs device token and FCM registration token for the client app instances when targeting a specific device to send a push notification. The JavaScript 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.

const sb = SendBird.getInstance();

if(sb) {
    if(Platform.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.
        });
    }
}

Step 3: Send and receive a push notification

Once you register the token, you can receive FCM data messages. FCM notification receiver should be defined in App.js to catch the message and notify the user if necessary. The example below is sample code for listening to push notifications using the react-native-fcm library.

import FCM, {
  FCMEvent
} from "react-native-fcm";

const showLocalNotificationWithAction = notif => {
    try {
        const data = JSON.parse(notif.sendbird);
        FCM.presentLocalNotification({
            title: data.sender ? data.sender.name : 'SendBird',
            body: data.message,
            priority: "high",
            show_in_foreground: true,
            click_action: "com.sendbird.sample.reactnative" // for ios
        });
    } catch(e) {
    }
}

FCM.on(FCMEvent.Notification, notif => {
    showLocalNotificationWithAction(notif);
});

The data above, which is parsed from a FCM data message, contains a set of key-value pairs 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.

{
    category: "messaging:offline_notification",
    type: string,            // Message Type, User or File or Admin
    message: string,        // User input message
    data: string,            // Custom data field
    custom_type: string,        // Message custom_type
    message_id: long,        // Message ID
    created_at: long,        // 13-digit timestamp
    app_id : string,        // application_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,        // messaging, group_messaging, 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.
}

Notification preferences

Push notifications can be turned on or off for a specific user.

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.
            });
        }
    }
}

Or, you can set push notification settings for individual channels.

// If you want to turn on push notifications for this channel, set this true.
groupChannel.setPushPreference(true, function(response, error) {
    if (error) {
        return;
    }

    // Do something in response to turning on push notifications.
});

If you want to snooze alarms (notifications) for some periods, invoke setDoNotDisturb().

const sb = SendBird.getInstance();

// The current logged-in user doesn't receive push notifications during the specified time.
sb.setDoNotDisturb(true, startHour, startMin, endHour, endMin, 'Asia/Seoul', function(response, error) {
    if (error) {
        return;
    }

    // Do something in response to setting 
});

Push notification message templates

Message templates define how a message is displayed when a push notification arrives to a user's device. You can choose between the default template and the alternative template, both of which are customizable.

Message templates

Text message File message
Default template {sender_name}: {message} (for example, John: Hello!) {filename} (for example, squirrel.jpg)
Alternative template New message arrived New file arrived

{sender_name}, {message}, and {filename} represent the corresponding string values. Use these fields to customize message templates from Dashboard Settings. The option is under Notifications > Push Notification Message Templates.

To determine what type of template applies to push notifications, call setPushTemplate(templateName, handler). The templateName is limited to the following: PUSH_TEMPLATE_DEFAULT, or PUSH_TEMPLATE_ALTERNATIVE.

const sb = SendBird.getInstance();

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

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

Note: The default configuration is PUSH_TEMPLATE_DEFAULT.

You can check your current settings with getPushTemplate().

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.
    }
});