JavaScript
Push Notifications

Push Notifications for JavaScript

Using our JavaScript SDK, you can send push notifications to users of your hybrid mobile app. Through those push notifications, your users can receive important information when the app is running in the background or a device is idle. You can also display the content of push notifications locally from your app while it is in the foreground.

Note: The JavaScript 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 JavaScript SDK.

Currently, the push notification functionality of the JavaScript 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 JavaScript SDK.

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

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 Installation > Initial Setup, Cloud Messaging, and Notifications pages.

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

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

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 push notifications and FCM messages

Once the tokens are registered, you can make the client app instance to receive push notifications and FCM messages. By following the instructions of the library documentation's Receiving Notifications part, you can receive and handle push notifications regardless of iOS and Android platforms. And with the instructions of the Receiving Firebase Cloud Messages part, you can 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 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.

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,             // Customized alert push message
    push_sound: string,             // The location of a sound file for push notifications
    audience_type: string,          // The type of audiences to receive push notifications
    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

The following shows how to register and unregister the current user's registration token to SendBird server to enable and disable push notifications in the user's client app.

Note: The registration/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.
            });
        }
    }
}             

If needed, at the current user's client app, you can determine the type of push notification trigger to customize when to deliver notifications. For customization, the following three options are provided:

  • all: the user receives push notifications for all new messages while offline, including mentioned messages.
  • off: no push notifications are delivered to the user.
  • mention_only: the user receives push notifications only for the mentioned messages while offline.
Light Color Skin
Copy
const sb = SendBird.getInstance();

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

At the channel level, you can also determine the type of push notification trigger by individual channel, and turn on or off notifications for the channel. For this, the following four options are provided:

  • all: the user receives push notifications for all new messages in the channel while offline, including mentioned messages.
  • off: no push notifications are delivered to the channel.
  • mention_only: the user receives push notifications only for the mentioned messages in the channel while offline.
  • default: the user's push notification trigger setting automatically applies to 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 push notifications for this channel, pass `false` as 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 suppress push notifications on the current user's client app during specific time of every day, use our Do Not Disturb feature like the following.

Note: You can also set a user's Do Not Disturb with the 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 
});

If you want to snooze push notifications for a specific period of time, use our snooze feature like the following.

Note: You can also snooze the notifications for a user with the 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 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 message templates

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

Message templates

Text messageFile message

Default template

{sender_name}: {message} (ex, John: Hello!)

{filename} (ex, squirrel.jpg)

Alternative template

New message arrived

New file arrived

The {sender_name}, {message}, and {filename} above represent the corresponding string values. Use these fields to customize message templates from your dashboard's Settings > Application > Notifications tab. The option is under the Push Notification Message Templates part.

To determine what type of template applies to push notifications, use the setPushTemplate() method. You can specify the name of a template 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.
});

Note: By default, a message template is PUSH_TEMPLATE_DEFAULT.

You can check your current setting with 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.
    }
});