Mobile Push Notifications API for PubNub JavaScript SDK
Mobile Push Notifications feature enables developers to bridge native PubNub publishing with 3rd-party push notification services including Google Android FCM (Firebase Cloud Messaging) and Apple iOS APNs (Apple Push Notification service).
By using the Mobile Push Notifications feature, developers can eliminate the need for developing, configuring, and maintaining additional server-side components for third-party push notification providers.
To learn more, read about Mobile Push Notifications.
Supported and recommended asynchronous patterns
PubNub supports Callbacks, Promises, and Async/Await for asynchronous JS operations. The recommended pattern is Async/Await and all sample requests in this document are based on it. This pattern returns a status only on detecting an error. To receive the error status, you must add the try...catch
syntax to your code.
Add Device to Channel
Requires Mobile Push Notifications add-on
This method requires that the Mobile Push Notifications add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
Enable mobile push notifications on the provided set of channels.
Method(s)
To run Adding Device to Channel
, you can use the following method(s) in the JavaScript SDK:
pubnub.push.addChannels({
channels: Array<string>,
device: string,
pushGateway: string,
environment: string,
topic: string
})
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
Operation Arguments | Hash | Yes | A hash of arguments. | |
channels | Array<string> | Yes | Specifies channel to associate with mobile push notifications. | |
device | string | Yes | The device ID to associate with mobile push notifications. | |
pushGateway | string | Yes | apns2 or gcm . | |
environment | string | Optional | development | Environment within which device should manage list of channels with enabled notifications (works only if pushGateway is set to apns2 ). Values: development or production . |
topic | string | Optional | Notifications topic name (usually it is bundle identifier of applicationfor Apple platform). Required only if pushGateway is set to apns2 . |
Basic Usage
Add Device to Channel
// for APNs2
try {
const result = await pubnub.push.addChannels({
channels: ["a", "b"],
device: "niceDevice",
pushGateway: "apns2",
environment: "production",
topic: "com.example.bundle_id"
});
console.log("operation done!");
result.channels.forEach(function (channel) {
console.log(channel);
});
show all 35 linesResponse
{
error: false,
operation: 'PNPushNotificationEnabledChannelsOperation',
statusCode: 200
}
List Channels For Device
Requires Mobile Push Notifications add-on
This method requires that the Mobile Push Notifications add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
Request for all channels on which push notification has been enabled using specified pushToken.
Method(s)
To run Listing Channels For Device
, you can use the following method(s) in the JavaScript SDK:
pubnub.push.listChannels({
device: string,
pushGateway: string,
environment: string,
topic: string
})
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
Operation Arguments | Hash | Yes | A hash of arguments. | |
device | string | Yes | The device ID to associate with mobile push notifications. | |
pushGateway | string | Yes | apns2 or gcm . | |
environment | string | Optional | development | Environment within which device should manage list of channels with enabled notifications (works only if pushGateway is set to apns2 ). Values: development or production . |
topic | string | Optional | Notifications topic name (usually it is bundle identifier of applicationfor Apple platform). Required only if pushGateway is set to apns2 . | |
start | string | Optional | Starting channel for pagination. Use the last channel from the previous page request. | |
count | number | Optional | Number of channels to return for pagination. Max of 1000 tokens at a time. Defaults to 500. |
Basic Usage
List Channels For Device
// for APNs2
try {
const result = await pubnub.push.listChannels({
device: "niceDevice",
pushGateway: "apns2",
environment: "production",
topic: "com.example.bundle_id"
});
console.log("operation done!");
result.channels.forEach(function (channel) {
console.log(channel);
});
} catch (status) {
console.log("operation failed w/ error:", status);
}
show all 31 linesResponse
// Example of status
{
error: false,
operation: 'PNPushNotificationEnabledChannelsOperation',
statusCode: 200
}
// Example of response
{
channels: [ 'a', 'b' ]
}
Remove Device From Channel
Requires Mobile Push Notifications add-on
This method requires that the Mobile Push Notifications add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
Disable mobile push notifications on provided set of channels.
Method(s)
To run Removing Device From Channel
, you can use the following method(s) in the JavaScript SDK:
pubnub.push.removeChannels({
channels: Array<string>,
device: string,
pushGateway: string,
environment: string,
topic: string
})
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
Operation Arguments | Hash | Yes | A hash of arguments. | |
channels | Array<string> | Yes | Specifies channel to associate with mobile push notifications. | |
device | string | Yes | The device ID to associate with mobile push notifications. | |
pushGateway | string | Yes | apns2 or gcm . | |
environment | string | Optional | development | Environment within which device should manage list of channels with enabled notifications (works only if pushGateway is set to apns2 ). Values: development or production . |
topic | string | Optional | Notifications topic name (usually it is bundle identifier of applicationfor Apple platform). Required only if pushGateway is set to apns2 . |
Basic Usage
Remove Device From Channel
// for APNs2
try {
const result = await pubnub.push.removeChannels({
channels: ["a", "b"],
device: "niceDevice",
pushGateway: "apns2",
environment: "production",
topic: "com.example.bundle_id"
});
console.log("operation done!");
result.channels.forEach(function (channel) {
console.log(channel);
});
show all 35 linesResponse
{
error: false,
operation: 'PNPushNotificationEnabledChannelsOperation',
statusCode: 200
}
Remove all mobile push notifications
Requires Mobile Push Notifications add-on
This method requires that the Mobile Push Notifications add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
Disable mobile push notifications from all channels registered with the specified pushToken.
Method(s)
To run Remove all mobile push notifications
, you can use the following method(s) in the JavaScript SDK:
pubnub.push.deleteDevice({
device: string,
pushGateway: string,
environment: string,
topic: string
})
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
Operation Arguments | Hash | Yes | A hash of arguments. | |
device | string | Yes | The device ID to associate with mobile push notifications. | |
pushGateway | string | Yes | apns2 or gcm . | |
environment | string | Optional | development | Environment within which device should manage list of channels with enabled notifications (works only if pushGateway is set to apns2 ). Values: development or production . |
topic | string | Optional | Notifications topic name (usually a bundle identifier of an application for the Apple platform). Required only if pushGateway is set to apns2 . |
Basic Usage
Remove all mobile push notifications
// for APNs2
try {
const result = await pubnub.push.deleteDevice({
device: "niceDevice",
pushGateway: "apns2",
environment: "production",
topic: "com.example.bundle_id"
});
console.log("operation done!");
result.channels.forEach(function (channel) {
console.log(channel);
});
} catch (status) {
show all 33 linesResponse
{
error: false,
operation: 'PNPushNotificationEnabledChannelsOperation',
statusCode: 200
}
Push Notification Format Configuration
Push notifications enforce specific message format requirements. Use these methods to configure your APNs and FCM mobile push notifications.
APNS2Configuration
APNS2
configuration type.
Method(s)
type APNS2Configuration = {
collapseId?: string,
expirationDate?: Date,
targets: Array<APNS2Target>
}
Parameter | Type | Required | Description |
---|---|---|---|
collapseId | string | Optional | Notification group / collapse identifier. Value will be used in APNS POST request as apns-collapse-id header value. |
expirationDate | Date | Optional | Date till which APNS will try to deliver notification to target device. Value will be used in APNS POST request as apns-expiration header value. |
targets | Array< APNS2Target> | Yes | List of topics which should receive this notification. |
APNSNotificationPayload
APNSNotificationPayload
instance provides access to options specific only to mobile push notifications sent with APNs.
Properties
Parameter | Type | Description |
---|---|---|
configurations | Array< APNSNotificationConfiguration> | List of HTTP/2-based APNs delivery configurations. |
notification | Hash | Hash with parameters which specify user-visible key-value pairs. |
payload | Hash | Platform specific notification payload. In addition to data required to make notification visual presentation it can be used to pass additional information which should be sent to remote device. |
silent | Boolean | Whether operation system should handle notification layout by default or not. alert , sound and badge will be removed from resulting payload if set to true . |
APNS2Target
APNS2
configuration target type.
Method(s)
type APNS2Target = {
topic: string,
environment?: 'development' | 'production',
excludedDevices?: Array<string>
}
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
topic | string | Yes | Notifications topic name (usually it is bundle identifier of applicationfor Apple platform). Required only if pushGateway is set to apns2 . | |
environment | string | Optional | development | Environment within which registered devices to which notifications should be delivered. Available:
|
excludedDevices | Array | Yes | List of devices (their push tokens) to which this notification shouldn't be delivered. |
FCMNotificationPayload
FCMNotificationPayload
instance provides access to options specific only to mobile push notifications sent with FCM.
Properties
Parameter | Type | Description |
---|---|---|
notification | Hash | Hash with parameters which specify user-visible key-value pairs. |
data | Hash | Custom key-value object with additional information which will be passed to device along with displayable notification information. All object and scalar type value should be converted to strings before passing to this object. Keys shouldn't match: from , message_type or start with google or gcm . Also as key can't be used any word defined in this table |
silent | Boolean | Whether operation system should handle notification layout by default or not. notification key with it's content will be moved from root level under data key. |
icon | String | Icon which should be shown on the left from notification title instead of application icon. |
tag | String | Unique notification identifier which can be used to publish update notifications (they will previous notification with same tag ). |
payload | Hash | Platform specific notification payload. In addition to data required to make notification visual presentation it can be used to pass additional information which should be sent to remote device. |
NotificationsPayload
NotificationsPayload
instance provides convenient method and properties which allow to setup notification for multiple platforms without getting into details how they should be formatted.
Builder instance contain additional set of properties which allow to fine tune payloads for particular platforms and even access to RAW payload dictionaries.
Method(s)
Parameter | Type | Description |
---|---|---|
subtitle | string | Additional information which may explain reason why this notification has been delivered. |
badge | number | Number which should be shown in space designated by platform (for example atop of application icon). |
sound | string | Path to file with sound or name of system sound which should be played upon notification receive. |
debugging | boolean | Whether PubNub service should provide debug information about devices which received created notifications payload. |
apns | APNSNotificationPayload | Access to APNS specific notification builder. |
fcm | FCMNotificationPayload | Access to FCM specific notification builder. |
PubNub.notificationPayload(
title: string,
body: string
)
Parameter | Type | Required | Description |
---|---|---|---|
title | string | Optional | Short text which should be shown at the top of notification instead of application name. |
body | string | Optional | Message which should be shown in notification body (under title line). |
buildPayload(
platforms: Array<string>
)
Parameter | Type | Required | Description |
---|---|---|---|
platforms | Array<string> | Yes | List of platforms for which payload should be added to final dictionary. Available:
|
Basic Usage
Create notification payload builder with pre-defined notification title and body:
let builder = PubNub.notificationPayload('Chat invitation',
'You have been invited to \'quiz\' chat');
let messagePayload = builder.buildPayload(['apns2', 'fcm']);
messagePayload.message = 'Max invited you to \'quiz\' chat room';
messagePayload.roomID = 'ewuiogw9vewg0';
pubnub.publish(
{
message: messagePayload,
channel: 'chat-bot',
},
function (status, response) {
// Handle publish results
}
);
let builder = PubNub.notificationPayload('Chat invitation',
'You have been invited to \'quiz\' chat');
Response
Hash with data, which can be sent with publish method call and trigger remote notifications for specified platforms.
Other Examples
Generate simple notification payload for FCM and APNS
let builder = PubNub.notificationPayload('Chat invitation',
'You have been invited to \'quiz\' chat');
builder.sound = 'default';
console.log(JSON.stringify(builder.buildPayload(['apns', 'fcm']), null, 2));
Output
{
"pn_apns": {
"aps": {
"alert": {
"body": "You have been invited to 'quiz' chat",
"title": "Chat invitation"
},
"sound": "default"
}
},
"pn_fcm": {
"notification": {
"body": "You have been invited to 'quiz' chat",
"title": "Chat invitation"
},
show all 22 linesGenerate simple notification payload for FCM and HTTP/2-based APNs (default configuration)
let builder = PubNub.notificationPayload('Chat invitation',
'You have been invited to \'quiz\' chat');
builder.apns.configurations = [{ targets: [{ topic: 'com.meetings.chat.app' }] }];
builder.sound = 'default';
console.log(JSON.stringify(builder.buildPayload(['apns2', 'fcm']), null, 2));
Output
{
"pn_apns": {
"aps": {
"alert": {
"body": "You have been invited to 'quiz' chat",
"title": "Chat invitation"
},
"sound": "default"
},
"pn_push": [
{
"targets": [
{
"environment": "development",
"topic": "com.meetings.chat.app"
show all 33 linesGenerate simple notification payload for FCM and HTTP/2-based APNs (custom configuration)
let configuration = [
{
collapseId: 'invitations',
expirationDate: new Date(Date.now() + 10000),
targets: [{ topic: 'com.meetings.chat.app' }]
}
];
let builder = PubNub.notificationPayload('Chat invitation',
'You have been invited to \'quiz\' chat');
builder.apns.configurations = [configuration];
console.log(JSON.stringify(builder.buildPayload(['apns2', 'fcm']), null, 2));
Output
{
"pn_apns": {
"aps": {
"alert": {
"body": "Chat invitation",
"title": "You have been invited to 'quiz' chat"
}
},
"pn_push": [
{
"collapse_id": "invitations",
"expiration": "2019-11-28T22:06:09.163Z",
"targets": [
{
"environment": "development",
show all 29 linesExample above show how to create notification payload which APNS will try to redeliver few times (if devices not active) and give up after 10 seconds since moment when it has been scheduled.
Additionally this invitation notification will be grouped along with other invitation notifications (using provided collapse_id
as group identifier) and shown as one in notification center.
Returns
Configured and ready to use NotificationsPayload
instance.