Feedback

WebWebNode.jsReact NativePhoneGapJavaScriptJavaScript V4 API Reference for Realtime Apps

 

These docs are for PubNub 4.0 for JavaScript which is our latest and greatest! For the docs of the older versions of the SDK, please check PubNub 3.0 for JavaScript, PubNub 3.0 for NodeJS and PubNub 3.0 for PhoneGap.

If you have questions about the PubNub for JavaScript SDK, please contact us at support@pubnub.com.

JavaScript V4 complete API reference for building Realtime Applications on PubNub, including basic usage and sample code

You must include the PubNub JavaScript SDK in your code before initializing the client.

<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.12.0.js"></script>
This function is used for initializing the PubNub Client API context. This function must be called before attempting to utilize any API functionality in order to establish account level credentials such as publishKey and subscribeKey.
To Initialize Pubnub you can use the following method(s) in the JavaScript V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    Operation Arguments Hash YesA hash of arguments.
    subscribeKey String YesSpecifies the subscribeKey to be used for subscribing to a channel. This key can be specified at initialization or along with a subscribe().
    publishKey String OptionalSpecifies the publishKey to be used for publishing messages to a channel. This key can be specified at initialization or along with a publish().
    cipherKey String OptionalIf passed, will encrypt the payloads.
    authKey StringOptionalIf PAM enabled, this key will be used on all requests.
    logVerbosity Boolean Optionalfalselog HTTP information.
    uuid String Optional SDK generated random uuidUUID to use, if not passed, a random will be generated.
    ssl Boolean Optional falseIf set to true, requests will be made over HTTPS, by default it is false unless the script is running on an https page.
    origin String Optional pubsub.pubnub.comIf a custom domain is required, SDK accepts it here.
    presenceTimeout Number Optional 300How long the server will consider the client alive for presence.
    heartbeatInterval Number OptionalNot SetHow often the client will announce itself to server.
    restore Boolean Optionalfalsetrue to allow catch up on the front-end applications.
    keepAliveBooleanOptionalfalseIf set to true, SDK will use the same TCP connection for each HTTP request, instead of opening a new one for each new request.
    keepAliveSettingsObjectOptional

    keepAliveMsecs: 1000


    freeSocketKeepAliveTimeout: 15000


    timeout: 30000


    maxSockets: Infinity


    maxFreeSockets: 256

    Set a custom parameters for setting your connection keepAlive if this is set to true.


    keepAliveMsecs: (Number) how often to send TCP KeepAlive packets over sockets.


    freeSocketKeepAliveTimeout: (Number) sets the free socket to timeout after freeSocketKeepAliveTimeout milliseconds of inactivity on the free socket.


    timeout: (Number) sets the working socket to timeout after timeout milliseconds of inactivity on the working socket.


    maxSockets: (Number) maximum number of sockets to allow per host.


    maxFreeSockets: (Number) maximum number of sockets to leave open in a free state.

    useInstanceId Boolean Optional InstanceId is created for each new instance done and this is a composition of the prefix pn- and an uuid v4, this instanceId is used for signing each request to the service.
var pubnub = new PubNub({
	subscribeKey: "mySubscribeKey",
	publishKey: "myPublishKey",
	cipherKey: "myCipherKey",
	authKey: "myAuthKey",
	logVerbosity: true,
	uuid: "myUniqueUUID",
	ssl: true,
	presenceTimeout: 130
})
It returns the Pubnub instance for invoking PubNub APIs like publish(), subscribe(), history(), hereNow(), etc.
  1. var pubnub = new PubNub({
    	subscribeKey: "mySubscribeKey",
    	publishKey: "myPublishKey",
    	ssl: true
    })
  2. In the case where a client will only read messages and never publish to a channel, you can simply omit the publishKey when initializing the client:
    // Initialize for Read Only Client
     
    var pubnub = new PubNub({
        subscribeKey : 'demo'
    });
  3. Under certain circumstances it useful to use a custom UUID to help in identifying your users.
    var pubnub = new PubNub ({
        subscribeKey: "mySubscribeKey",
        uuid: "myUniqueUUID"
    })
    
  4. This examples demonstrates how to enable PubNub Transport Layer Encryption with SSL. Just initialize the client with ssl set to true. The hard work is done, now the PubNub API takes care of the rest. Just subscribe and publish as usual and you are good to go.
    var pubnub = new PubNub({
    	subscribeKey: "mySubscribeKey",
    	publishKey: "myPublishKey",
    	cipherKey: "myCipherKey",
    	authKey: "myAuthKey",
    	logVerbosity: true,
    	uuid: "myUniqueUUID",
    	ssl: true,
    	presenceTimeout: 130
    })
  5.  

    Anyone with the secretKey can grant and revoke permissions to your app. Never let your secretKey be discovered, and to only exchange it / deliver it securely. Only use the secretKey on secure environments such as node.js application or other server-side platforms.

    When you init with secretKey, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.

    For applications that will administer PAM permissions, the API is initialized with the secretKey as in the following example:
    var pubnub = new PubNub({
        subscribeKey: "mySubscribeKey",
        publishKey: "myPublishKey",
        secretKey: "secretKey"
    })
    
    Now that the pubnub object is instantiated the client will be able to access the PAM functions. The pubnub object will use the secretKey to sign all PAM messages to the PubNub Network.
These functions are used to set/get a user ID on the fly.
To set/get UUID you can use the following method(s) in JavaScript V4 SDK
  1. ParameterTypeRequiredDescription
    uuid String YesUUID to set.
  2. This method doesn't take any arguments.
  3. This method doesn't take any arguments.
pubnub.setUUID("CustomUUID")
pubnub.getUUID();
PubNub.generateUUID();
  1. var channel = PubNub.generateUUID();
    
    pubnub.subscribe({
        channels: [channel]
    })
  2. var newUUID = PubNub.generateUUID();
    
    var pubnub = new PubNub ({ 
        uuid: newUUID, 
        subscribeKey: "mySubscribeKey",
        publishKey: "myPublishKey",
        secretKey: "secretKey"
    });
  3. var randomAuthKey = PubNub.generateUUID();
       
    var pubnub = new PubNub ({
    	authKey: randomAuthKey, 
    	subscribeKey: "mySubscribeKey",
    	publishKey: "myPublishKey",
    	secretKey: "secretKey"
    });
This function provides the capability to reset a user's auth Key.
Typically auth Key is specified during initialization for PubNub Access Manager enabled applications. In the event that auth Key has expired or a new auth Key is issued to the client from a Security Authority, the new auth Key can be sent using setAuthKey().
To Set Authentication Key you can use the following method(s) in the JavaScript V4 SDK
  1. ParameterTypeRequiredDescription
    key String YesAuth key to set.
pubnub.setAuthKey("my_authkey")
None.
To set/get filters you can use the following methods.
  1. ParameterTypeRequiredDescription
    filterExpressionStringYesPSV2 feature to subscribe with a custom filter expression.
  2. This method doesn't take any arguments.
pubnub.setFilterExpression("such=wow");
pubnub.getFilterExpression();
The publish() function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid publishKey at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.
Messages in transit can be secured from potential eavesdroppers with SSL/TLS by setting ssl to true during initialization.
 
Publish Anytime
It is not required to be subscribed to a channel in order to publish to that channel.
Message Data:
The message argument can contain any JSON serializable data, including: Objects, Arrays, Ints and Strings. Message data should not contain special JavaScript V4 classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.
Message Size:
The maximum number of characters per message is 32K by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5KB) providing optimal network performance.
If the message you publish exceeds the configured size, you will receive the following message:
Message Too Large Error
["PUBLISHED",[0,"Message Too Large","13524237335750949"]]

For further details please check: https://support.pubnub.com/support/discussions/topics/14000006322

Message Publish Rate:
Messages can be published as fast as bandwidth conditions will allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber cannot keep pace with the publisher.
For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.
Publishing to Multiple Channels.
It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.
Publishing Messages Reliably.
There are some best practices to ensure messages are delivered when publishing to a channel:
  • Publish to any given channel in a serial manner (i.e. not concurrently).
  • Check that the return code is success (e.g. [1,"Sent","136074940..."])
  • Publish the next message only after receiving a success return code.
  • If a failure code is returned ([0,"blah","<timetoken>"]), retry the publish.
  • Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
  • Throttle publish bursts in accordance with your app's latency needs e.g. Publish no faster than 5 msgs per second to any one channel.
 
Do Not Use JSON.stringify!
It is important to note that you should not use JSON.stringify() when sending signals/messages via PubNub. Why? Because the serialization is done for you automatically. Instead just pass the full object as the message payload. PubNub takes care of everything for you.
 

Single string messages are automatically sent to APNS if mobile push is enabled and devices are registered for push on that channel. So if you use encryption (cipher key in the init) and publish the message, then it will be sent to APNS if there is a device(s) registered to that channel.

This is a legacy feature and will be deprecated soon.

To Publish a message you can use the following method(s) in the JavaScript V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    Operation Arguments Hash YesA hash of arguments.
    message ObjectYesThe message may be any valid JSON type including objects, arrays, strings, and numbers.
    channel String YesSpecifies channel name to publish messages to.
    storeInHistory Boolean Optionaltrue

    If true the messages are stored in history.

    If storeInHistory is not specified, then the history configuration on the key is used.

    sendByPost Boolean OptionalfalseIf true the messages sent via POST.
    meta Object OptionalPublish extra meta with the request.
    ttlNumberOptional
    Set a per message time to live in storage.
    1. If storeInHistory = true, and ttl = 0, the message stored with no expiry time.
    2. If storeInHistory = true and ttl = X (X is an Integer value), the message is stored with an expiry time of X hours.
    3. If storeInHistory = false, the ttl parameter is ignored.
    4. If ttl is not specified, then expiration of the message defaults back to the expiry value for the key.
    callback FunctionOptionalExecutes on a successful/unsuccessful publish.

Publish a message to a channel:

pubnub.publish(
    {
        message: { 
            such: 'object' 
        },
        channel: 'my_channel',
        sendByPost: false, // true to send via post
        storeInHistory: false, //override default storage options
        meta: { 
            "cool": "meta"
        }   // publish extra meta with the request
    }, 
    function (status, response) {
        if (status.error) {
            // handle error
            console.log(status)
        } else {
            console.log("message Published w/ timetoken", response.timetoken)
        }
    }
);
 
Before running the above publish example, either using the Debug Console, or in a separate script running in a separate terminal window, subscribe to the same channel that is being published to.
type PublishResponse = {
    timetoken: number
}
  1. var newMessage = {
        text: 'Hi There!'
    }
    pubnub.publish(
        {
            message: newMessage,
            channel: 'my_channel'
        }, 
        function(status, response) {
            if (status.error) {
                console.log("publishing failed w/ status: ", status);
            } else {
                console.log("message published w/ server response: ", response);
            }
        }
    );
  2. pubnub.publish(
        {
            message: 'hello!',
            channel: 'my_channel',
            storeInHistory: true,
            ttl: 10
        }, 
        function(status, response) {
            if (status.error) {
                console.log("publishing failed w/ status: ", status);
            } else {
                console.log("message published w/ server response: ", response);
            }
        }
    );
  3. pubnub.publish(
        {
            message: 'hello world!',
            channel: 'ch1' 
        }, 
        (status, response) => {
            console.log(status); // {error: false, operation: "PNPublishOperation", statusCode: 200}
            console.log(response); // {timetoken: "14920301569575101"}
        }
    );
  4. pubnub.publish(
        {
            message: 'hello world!',
            channel: 'ch1' 
        }, 
        (status, response) => {
            console.log(status); // {error: true, operation: "PNPublishOperation", errorData: Error, category: "PNNetworkIssuesCategory"}
            console.log(response); // undefined
        }
    );
  5. pubnub.publish(
        {
            message: 'hello world!', 
            channel: 'ch1' 
        }, 
        (status, response) => {
            console.log(status); // {error: true, operation: "PNPublishOperation", statusCode: 400, errorData: Error, category: "PNBadRequestCategory"}
            console.log(response); // undefined
        }
    );
  6. pubnub.publish(
        { 
            message: 'hello world!', 
            channel: 'ch1' 
        }, 
        (status, response) => {
            console.log(status); // {message: "Missing Channel", type: "validationError", error: true}
            console.log(response); // undefined
        }
    );
  7. pubnub.publish(
        {
            message: 'hello world!',
            channel: 'ch1' 
        },
        (status, response) => {
            console.log(status); // {message: "Missing Message", type: "validationError", error: true}
            console.log(response); // undefined
        }
    );
  8. pubnub.publish({
        message: { 
            such: 'object'
        },
        channel: 'my_channel',
        sendByPost: false, // true to send via post
        storeInHistory: false, //override default storage options
        meta: { 
            "cool": "meta"
        }   // publish extra meta with the request
    }).then((response) => {
        console.log(response)
    }).catch((error) => {
        console.log(error)
    });
  9. var newMessage = {
        text: 'Hi There!'
    }
    pubnub.publish({
        message: newMessage,
        channel: 'my_channel'
    }).then((response) => {
        console.log(response)
    }).catch((error) => {
        console.log(error)
    });
  10. pubnub.publish({
        message: 'hello!',
        channel: 'my_channel',
        storeInHistory: true,
        ttl: 10
    }).then((response) => {
        console.log(response)
    }).catch((error) => {
        console.log(error)
    });
  11. pubnub.publish({ 
        message: 'hello world!',
        channel: 'ch1' 
    }).then((response) => {
        console.log(response); // {timetoken: "14920301569575101"}
    }).catch((err) => {
        console.log(err);
    });
  12. pubnub.publish({ 
        message: 'hello world!',
        channel: 'ch1' 
    }).then((response) => {
       console.log(response);
    }).catch((err) => {
        console.log(err); // {error: true, operation: "PNPublishOperation", errorData: Error, category: "PNNetworkIssuesCategory"}
    });
  13. pubnub.publish({ 
        message: 'hello world!',
        channel: 'ch1' 
    }).then((response) => {
        console.log(response);
    }).catch((err) => {
        console.log(err); // {error: true, operation: "PNPublishOperation", statusCode: 400, errorData: Error, category: "PNBadRequestCategory"}
    });
  14. pubnub.publish({ 
        message: 'hello world!',
        channel: 'ch1' 
    }).then((response) => {
        console.log(response);
    }).catch((err) => {
        console.log(err); // {message: "Missing Channel", type: "validationError", error: true}
    });
  15. pubnub.publish({ 
        message: 'hello world!', 
        channel: 'ch1' 
    }).then((response) => {
        console.log(response);
    }).catch((err) => {
        console.log(err); // {message: "Missing Message", type: "validationError", error: true}
    });
The fire endpoint allows the client to send a message to BLOCKS Event Handlers. These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler. The message sent via fire() is not replicated, and so will not be received by any subscribers to the channel. The message is also not stored in history.
To Fire a message you can use the following method(s) in the JavaScript V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    Operation Arguments Hash YesA hash of arguments.
    message ObjectYesThe message may be any valid JSON type including objects, arrays, strings, and numbers.
    channel String YesSpecifies channel name to publish messages to.
    sendByPost Boolean OptionalfalseIf true the messages sent via POST.
    meta Object OptionalPublish extra meta with the request.
    callback FunctionOptionalExecutes on a successful/unsuccessful publish.

Fire a message to a channel:

pubnub.fire(
    {
        message: { 
            such: 'object' 
        },
        channel: 'my_channel',
        sendByPost: false, // true to send via post
        meta: { 
            "cool": "meta"
        }   // fire extra meta with the request
    }, 
    function (status, response) {
        if (status.error) {
            // handle error
            console.log(status)
        } else {
            console.log("message published w/ timetoken", response.timetoken)
        }
    }
);
  1. pubnub.fire({
        message: { 
            such: 'object'
        },
        channel: 'my_channel',
        sendByPost: false, // true to send via post
        meta: { 
            "cool": "meta"
        }   // fire extra meta with the request
    }).then((response) => {
        console.log(response);
    }).catch((error) => {
        console.log(error)
    });
This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel. To subscribe to a channel the client must send the appropriate subscribeKey at initialization.
By default a newly subscribed client will only receive messages published to the channel after the subscribe() call completes.
 

You can be notified of connectivity via the listener, on establishing connection the statusEvent.category returns PNConnectedCategory.

By waiting for the connect event to return before attempting to publish, you can avoid a potential race condition on clients that subscribe and immediately publish messages before the subscribe has completed.

 Unsubscribing from all the channel(s) and then subscribing to a new channel Y is not the same than Subscribing to the channel Y and then unsubscribing from the previously subscribe channel(s). Unsubscribing from all the channels resets the timetoken and thus, there could be some gaps in the subscription that may lead to a message loss.
To Subscribe to a channel you can use the following method(s) in the JavaScript V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    Operation Arguments Hash YesA hash of arguments.
    channels ArrayYesSpecifies the channels to subscribe to. It is possible to specify multiple channels as a list or as an array.
    channelGroupsArraySpecifying either channels or channelGroups is mandatorySpecifies the channelGroups to subscribe to.
    withPresence Boolean OptionalfalseIf true it also subscribes to presence instances.
    timetoken Number OptionalSpecifies timetoken from which to start returning any available cached messages. Message retrieval with timetoken is not guaranteed and should only be considered a best-effort service.
Subscribe to a channel:
pubnub.subscribe({
    channels: ['my_channel'],
});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
ObjectDescription
categoryPNConnectedCategory
operationPNSubscribeOperation
affectedChannelsThe channels affected in the operation, of type array.
subscribedChannelsAll the current subscribed channels, of type array.
affectedChannelGroupsThe channel groups affected in the operation, of type array.
lastTimetokenThe last timetoken used in the subscribe request, of type long.
currentTimetokenThe current timetoken fetched in the subscribe response, which is going to be used in the next request, of type long.
{
    category: 'PNConnectedCategory',
    operation: 'PNSubscribeOperation',
    affectedChannels: ['my_channel_1'],
    subscribedChannels: ['my_channel_1'],
    affectedChannelGroups: [],
    lastTimetoken: '14974492380756600',
    currentTimetoken: '14974492384874375'
}
ObjectDescription
channelThe channel for which the message belongs.
subscriptionThe channel group or wildcard subscription match (if exists).
timetokenPublish timetoken.
messageThe payload.
{
    actualChannel: null,
    channel: "my_channel_1",
    message: "Hello World!",
    publisher: "pn-58e1a647-3e8a-4c7f-bfa4-e007ea4b2073",
    subscribedChannel: "my_channel_1",
    subscription: null,
    timetoken: "14966804541029440"
}
ObjectDescription
actionCan be join, leave, state-change or timeout.
channelThe channel for which the message belongs.
occupancyNo. of users connected with the channel.
stateUser State.
subscriptionThe channel group or wildcard subscription match (if exists)
timestampCurrent timetoken.
timetokenPublish timetoken.
uuidUUIDs of users who are connected with the channel.
{
    category: 'PNConnectedCategory',
    operation: 'PNSubscribeOperation',
    affectedChannels: ['my_channel_1'],
    subscribedChannels: ['my_channel_1'],
    affectedChannelGroups: [],
    lastTimetoken: '14974492380756600',
    currentTimetoken: '14974492384874375'
}
  1. It is possible to subscribe to more than one channel over a single TCP socket by taking advantage of Multiplexing feature. See the Multiplexing section for more info on this feature as well as the examples below using a list or an array to specify channel name.
    pubnub.subscribe({
        channels: ['my_channel_1', 'my_channel_2', 'my_channel_3']
    });
  2. For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending -pnpres to the channel name. For example the channel named my_channel would have the presence channel named my_channel-pnpres.
    pubnub.subscribe({
    	channels: ['my_channel'],
    	withPresence: true
    });
    
    {
    	"action": "join",
    	"timestamp": 1345546797,
    	"uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
    	"occupancy": 2
    }
    
    {
        "action" : "leave",
        "timestamp" : 1345549797,
        "uuid" : "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
        "occupancy" : 1
    }
    {
    	"action": "timeout",
    	"timestamp": 1345549797,
    	"uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
    	"occupancy": 0
    }
    
    {
    	"action": "state-change",
    	"uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
    	"timestamp": 1345549797,
    	"data": {
    		"isTyping": true
    	}
    }
    
    {
    	"action":"interval",
    	"timestamp":1474396578,
    	"occupancy":2
    }
    

    When a channel is in interval mode with presence_deltas pnconfig flag enabled, the interval message may also include the following fields which contain an array of changed UUIDs since the last interval message.

    • joined
    • left
    • timedout

    For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:

    {
        "action" : "interval",
        "occupancy" : <# users in channel>,
        "timestamp" : <unix timestamp>,
        "joined" : ["uuid2", "uuid3"],
        "timedout" : ["uuid1"]
    }
    

    If the full interval message is greater than 30KB (since the max publish payload is ∼32KB), none of the extra fields will be present. Instead there will be a here_now_refresh boolean field set to true. This indicates to the user that they should do a hereNow request to get the complete list of users present in the channel.

    {
        "action" : "interval",
        "occupancy" : <# users in channel>,
        "timestamp" : <unix timestamp>,
        "here_now_refresh" : true
    }
    
  3. Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. E.g., if you subscribe to a.* you will get all messages for a.b, a.c, a.x. The wildcarded * portion refers to any portion of the channel string name after the dot (.).
    pubnub.subscribe({
        channels: ['ab.*'] 
    });
  4. You can set state for a uuid during a subscribe by using the state parameter. Simply specify the desired key/value pairs as a JSON object.
    var pubnub = new PubNub({ 
    	/* initiation arguments */ 
    })
    pubnub.addListener({
    	status: function(statusEvent) {
    		if (statusEvent.category === "PNConnectedCategory") {
    			var newState = {
    				new: 'state' 
    			};
    			pubnub.setState(
    				{ 
    					state: newState 
    				}, 
    				function (status) {
    					// handle state setting response
    				}
    			);
    		}
    	},
    	message: function(message) {
    		// handle message
    	},
    	presence: function(presenceEvent) {
    		// handle presence
    	}
    })
    
    pubnub.subscribe({ 
    	channels: ['ch1', 'ch2', 'ch3'] 
    });
  5. pubnub.subscribe({
    	channelGroups: ['my_channelGroup']
    });
  6. pubnub.subscribe({
        channelGroups: ['family'],
        withPresence: true
    });
  7. pubnub.subscribe({
        channelGroups: ['my_channelGroup1', 'my_channelGroup2', 'my_channelGroup3']
    });
  8. pubnub.subscribe({
        channels: ['my_channel'],
        channelGroups: ['my_channelGroup']
    });
When subscribed to a single channel, this function causes the client to issue a leave from the channel and close any open socket to the PubNub Network. For multiplexed channels, the specified channel(s) will be removed and the socket remains open until there are no more channels remaining in the list.
 Unsubscribing from all the channel(s) and then subscribing to a new channel Y is not the same than Subscribing to the channel Y and then unsubscribing from the previously subscribe channel(s). Unsubscribing from all the channels resets the timetoken and thus, there could be some gaps in the subscription that may lead to a message loss.
To Unsubscribe from a channel you can use the following method(s) in the JavaScript V4 SDK:
  1. ParameterTypeRequiredDescription
    Operation ArgumentsHashYesA hash of arguments.
    channelsArray YesSpecifies the channel to unsubscribe from.
    channelGroups ArraySpecifying either channels or channelGroups is mandatorySpecifies the channelGroups to unsubscribe from.
Unsubscribe from a channel:
pubnub.unsubscribe({
    channels: ['my_channel']
})
The output below demonstrates the response to a successful call:
{
	"action" : "leave"
}
  1. pubnub.unsubscribe({
    	channels: ['chan1', 'chan2', 'chan3']
    })
    
    {
    	"action" : "leave"
    }
    
  2. pubnub.unsubscribe({
        channelGroups : ['demo_group1', 'demo_group2']
    });
Unsubscribe from all channels and all channel groups
  • unsubscribeAll()
pubnub.unsubscribeAll();
None

You can be notified of connectivity status, message and presence notifications via the listeners.

Listeners should be added before calling the method.

pubnub.addListener({
   
    message: function(m) {
        // handle message
        var channelName = m.channel; // The channel for which the message belongs
        var channelGroup = m.subscription; // The channel group or wildcard subscription match (if exists)
        var pubTT = m.timetoken; // Publish timetoken
        var msg = m.message; // The Payload
    },
    presence: function(p) {
        // handle presence
        var action = p.action; // Can be join, leave, state-change or timeout
        var channelName = p.channel; // The channel for which the message belongs
        var occupancy = p.occupancy; // No. of users connected with the channel
        var state = p.state; // User State
        var channelGroup = p.subscription; //  The channel group or wildcard subscription match (if exists)
        var presenceEventTime = p.timestamp; // Presence event timetoken
        var uuid = p.uuid; // UUIDs of users who are connected with the channel
    },
    status: function(s) {
        // handle status
        var category = s.category; //PNConnectedCategory
        var operation = s.operation; //PNSubscribeOperation
        var affectedChannels = s.affectedChannels; //The channels affected in the operation, of type array.
        var subscribedChannels = s.subscribedChannels; //All the current subscribed channels, of type array.
        var affectedChannelGroups = s.affectedChannelGroups; //The channel groups affected in the operation, of type array.
        var lastTimetoken = s.lastTimetoken; //The last timetoken used in the subscribe request, of type long.
        var currentTimetoken = s.currentTimetoken; //The current timetoken fetched in the subscribe response, which is going to be used in the next request, of type long.
    }
})
var existingListener = {
    message: function() {
    } 
}

pubnub.removeListener(existingListener)
CategoriesDescription
PNNetworkUpCategory
SDK detected that network is online.
PNNetworkDownCategory
SDK detected that network is down.
PNNetworkIssuesCategory
A subscribe event experienced an exception when running.
PNReconnectedCategory
SDK was able to reconnect to pubnub.
PNConnectedCategory
SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed).
PNAccessDeniedCategory
PAM permission failure.
PNMalformedResponseCategory
JSON parsing crashed.
PNBadRequestCategory
Server rejected the request.
PNDecryptionErrorCategory
If using decryption strategies and the decryption fails.
PNTimeoutCategory
Failure to establish connection due to timeout.
You can obtain information about the current state of a channel including a list of unique user-ids currently subscribed to the channel and the total occupancy count of the channel by calling the hereNow() function in your application.
To call Here Now you can use the following method(s) in the JavaScript V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    Operation ArgumentsHashYesA hash of arguments.
    channels ArrayOptionalSpecifies the channel name to return occupancy results. If channel is not provided, hereNow() will return data for all channels.
    channelGroups ArrayOptionalThe channel group for which here now information should be received.
    includeUUIDs Boolean OptionaltrueSetting uuid to false disables the return of uuids.
    includeState BooleanOptionalfalseSetting state to true enables the return of subscriber state information.
    callbackFunctionOptionalExecutes on a successful/unsuccessful hereNow.
pubnub.hereNow(
    {
        channels: ["ch1"], 
        channelGroups : ["cg1"],
        includeUUIDs: true,
        includeState: true 
    },
    function (status, response) {
        // handle status, response
    }
);
type hereNowResponse = {
    totalChannels: number, // totalChannels = get total of channels
    totalOccupancy: number, // totalOccupancy = get total of occupancies
    channels: object // channels = get a map with values for each channel with uuids and states for each occupant of the channel
}
  1. pubnub.hereNow(
        {
            channels: ["my_channel"],
            includeState: true
        },
        function (status, response) {
            // handle status, response
        }
    );
    {
        totalChannels: 1,
        totalOccupancy: 3,
        channels: {
            myChannel1: {
                name: "myChannel1",
                occupancy: 3,
                occupants: [
                    {
                        uuid: "User 524"
                    },
                    {
                        state:
                        {
                            age: 18
                        },
                        uuid: "User 270"
                    },
                    {
                        state:
                        {
                            age: 24
                        },
                        uuid: "User 594"
                    }
                ]
            }
        }
    }
  2. You can return only the occupancy information for a single channel by specifying the channel and setting uuids to false:
    pubnub.hereNow(
        {
            channels: ["my_channel"],
            includeUUIDs: false
        },
        function (status, response) {
            // handle status, response
        }
    );
    {
        "status": 200,
        "message": "OK",
        "payload": {
            "channels": {
                "81d8d989-b95f-443c-a726-04fac323b331": { 
                    "uuids": [ "70fc1140-22b5-4abc-85b2-ff8c17b24d59" ], 
                    "occupancy": 1 
                },
                "81b7a746-d153-49e2-ab70-3037a75cec7e": { 
                    "uuids": [ "91363e7f-584b-49cc-822c-52c2c01e5928" ],
                    "occupancy": 1
                },
                "c068d15e-772a-4bcd-aa27-f920b7a4eaa8": { 
                    "uuids": [ "ccfac1dd-b3a5-4afd-9fd9-db11aeb65395" ],
                    "occupancy": 1
                }
            },
            "total_channels": 3,
            "total_occupancy": 3
        },
        "service": "Presence"
    }
    
  3. You can return the list of uuids and occupancy for all channels by omitting the channel:
    pubnub.hereNow(
        {
            includeUUIDs: true
        },
        function (status, response) {
            // handle status, response
        }
    );
    {
        "total_channels" : 2,
        "total_occupancy" : 3,
        "channels" : {
            "lobby" : {
                "occupancy" : 1,
                "uuids" : [
                    "dara01"
                ]
            },
            "game01" : {
                "occupancy" : 2,
                "uuids" : [
                    "jason01",
                    "jason02"
                ]
            }
        }
    }
    
  4. You can return only the occupancy information (Global Here Now) by omitting the channel name
    pubnub.hereNow(
        {
            includeUUIDs: true,
            includeState: true
        },
        function (status, response) {
            // handle status, response
        }
    );
    {
        "status": 200,
        "message": "OK",
        "payload": {
            "channels": {
                "81d8d989-b95f-443c-a726-04fac323b331": { 
                    "uuids": [ "70fc1140-22b5-4abc-85b2-ff8c17b24d59" ], 
                    "occupancy": 1 
                },
                "81b7a746-d153-49e2-ab70-3037a75cec7e": { 
                    "uuids": [ "91363e7f-584b-49cc-822c-52c2c01e5928" ],
                    "occupancy": 1
                },
                "c068d15e-772a-4bcd-aa27-f920b7a4eaa8": { 
                    "uuids": [ "ccfac1dd-b3a5-4afd-9fd9-db11aeb65395" ],
                    "occupancy": 1
                }
            },
            "total_channels": 3,
            "total_occupancy": 3
        },
        "service": "Presence"
    }
    
  5. pubnub.hereNow(
        {
            channelGroups : ["my_channel_group"]
        },
        function (status, response) {
            // handle status, response
        }
    );
    {
    	"status": 200,
    	"message": "OK",
    	"payload": {
    		"total_occupancy": 2,
    		"total_channels": 2,
    		"channels": {
    			"ch1": {
    				"occupancy": 1,
    				"uuids": [
    					{
    						"uuid": "user1",
    						"state": {
    							"age": 10
    						}
    					}
    				]
    			},
    			"ch2": {
    				"occupancy": 1,
    				"uuids": [
    					{
    						"uuid": "user1",
    						"state": {
    							"age": 10
    						}
    					}
    				]
    			}
    		}
    	},
    	"service": "Presence"
    }
  6. pubnub.hereNow({
        channels: ["ch1"], 
        channelGroups : ["cg1"],
        includeUUIDs: true,
        includeState: true
    }).then((response) => { 
        console.log(response) 
    }).catch((error) => { 
        console.log(error)
    });
  7. pubnub.hereNow({
        channels: ["my_channel"],
        includeState: true
    }).then((response) => { 
        console.log(response) 
    }).catch((error) => { 
        console.log(error) 
    });
  8. You can return only the occupancy information for a single channel by specifying the channel and setting uuids to false:
    pubnub.hereNow({
        channels: ["my_channel"],
        includeUUIDs: false
    }).then((response) => { 
        console.log(response) 
    }).catch((error) => { 
        console.log(error) 
    });
  9. You can return the list of uuids and occupancy for all channels by omitting the channel:
    pubnub.hereNow({
        includeUUIDs: true
    }).then((response) => { 
        console.log(response) 
    }).catch((error) => { 
        console.log(error) 
    });
  10. You can return only the occupancy information (Global Here Now) by omitting the channel name
    pubnub.hereNow({
        includeUUIDs: true,
        includeState: true
    }).then((response) => { 
        console.log(response) 
    }).catch((error) => { 
        console.log(error) 
    });
  11. pubnub.hereNow({
        channelGroups : ["my_channel_group"]
    }).then((response) => { 
        console.log(response) 
    }).catch((error) => { 
        console.log(error) 
    });
You can obtain information about the current list of channels to which a uuid is subscribed to by calling the whereNow function in your application.
 
If the app is killed/crashes and restarted (or the page containing the PubNub instance is refreshed on the browser) within the heartbeat window no timeout event is generated.
To call whereNow you can use the following method(s) in the JavaScript V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    Operation ArgumentsHashYesA hash of arguments.
    uuid String Optionalcurrent uuidSpecifies the uuid to return channel list for.
    callbackFunctionOptionalExecutes on a successful/unsuccessful whereNow.
You simply need to define the uuid and the callback function to be used to send the data to as in the example below.
pubnub.whereNow(
    {
        uuid: "uuid"
    },
    function (status, response) {
        // handle status, response
    }
);

type WhereNowResponse = {
    channels: Array<string>,
}

  1. pubnub.whereNow({ 
        uuid: "uuid"
    }).then((response) => {
        console.log(response)
    }).catch((error) => {
        console.log(error)
    });
The state API is used to set/get key/value pairs specific to a subscriber uuid.
State information is supplied as a JSON object of key/value pairs.
  1. ParameterTypeRequiredDescription
    Operation ArgumentsHashYesA hash of arguments.
    channelsArrayOptionalEither channels or channelGroups should be provided, Specifies the channels to set the state.
    channelGroupsArrayOptionalEither channels or channelGroups should be provided, Specifies the Channel Group to set the state
    state ObjectOptional

    JSON object of key/value pairs with supported data-types of int, float and string. Nesting of key/values is not permitted and key names beginning with prefix pn are reserved.

    If the state parameter is undefined, the current state for the specified uuid will be returned. If a specified key already exists for the uuid it will be over-written with the new value. Key values can be deleted by setting the particular value to null.

    callbackFunctionOptionalExecutes on a successful/unsuccessful setState.
  1. ParameterTypeRequiredDefaultsDescription
    Operation ArgumentsHashYesA hash of arguments.
    uuidStringOptionalcurrent uuidThe subscriber uuid to get the current state.
    channelsArrayOptionalEither channels or channelGroups should be provided, Specifies the channels to get the state.
    channelGroups ArrayOptionalEither channels or channelGroups should be provided, Specifies the Channel Group to get the state.
    callbackFunctionOptionalExecutes on a successful/unsuccessful getState.
pubnub.setState(
    {
        state: newState,
        channels: ['ch1'],
        channelGroups: ['cg1']
    },
    function (status, response) {
        // handle status, response
    }
);
pubnub.getState(
    {
        uuid: "uuid",
        channels: ['ch1'],
        channelGroups: ['cg1']
    },
    function (status, response) {
        // handle status, response
    }
);
type SetStateResponse = {
    state: Object
}
type GetStateResponse = {
    channels: Object
}
  1. pubnub.setState({
        state: newState,
        channels: ['ch1'],
        channelGroups: ['cg1']
    }).then((response) => { 
        console.log(response) 
    }).catch((error) => { 
        console.log(error)
    });
  2. pubnub.getState({
        uuid: "uuid",
        channels: ['ch1'],
        channelGroups: ['cg1']
    }).then((response) => { 
        console.log(response) 
    }).catch((error) => { 
        console.log(error)
    });
This function establishes access permissions for PubNub Access Manager (PAM) by setting the read or write attribute to true. A grant with read or write set to false (or not included) will revoke any previous grants with read or write set to true.
Permissions can be applied to any one of three levels:
  1. Application level privileges are based on subscribeKey applying to all associated channels.
  2. Channel level privileges are based on a combination of subscribeKey and channel name.
  3. User level privileges are based on the combination of subscribeKey, channel and auth Key.
 
If your server is performing Grants, please ensure that you have configured NTP on your server to keep the clock in sync. This is to prevent system clock drift leading to 400 Invalid Timestamp error response.
https://support.pubnub.com/support/solutions/articles/14000043626-why-do-i-get-invalid-timestamp-when-i-try-to-grant-permission-using-access-manager-
When a user attempts to access a PubNub resource, PAM will evaluate any existing rules using the following order of precedence before access to a channel is granted to the user:
  1. Application Level - PAM privileges are always evaluated first at the Application level. If either read or write attribute is set to true for a subscribeKey, PAM will immediately grant access for that attribute without proceeding to check permissions at either Channel or User levels. If an attribute is set to false at the Application level, PAM proceeds to evaluate the attribute at the next most granular level.
     

    Use application level grants with caution

    When access is granted on an application level, all channels and users will have access.

    Application level grants can also happen due to a bug in your code. e.g. Null parameters for channels and auth-keys can cause accidental application level grants.

  2. Channel Level - After first verifying an attribute at the Application level, PAM evaluates the attribute at the Channel level. If an attribute is set to true for a combination of subscribeKey and channel, PAM grants access for that attribute at the Channel level without proceeding to check whether there may be user level permissions.
  3. User Level - As a final step PAM evaluates the attributes at the User level. If an attribute is set to true for subscribeKey, channel and auth Key, access is granted for that attribute.
 
If an argument of the grant is not provided, an expected default will be assumed.
  • read and write arguments default to false
  • no auth Key results in channel-level grant
  • no channel results in application-level grant
No Permissions - If no permissions were granted at any of the three levels, the user will be denied access to the PubNub resource and receive a 403 error message. This is the default behavior for a PAM enabled application.
 
Note that privileges specifically granted to an application's subscribeKey always take precedence over privileges granted to channel or auth Key. Therefore an application that requires authentication at the userlevel should not grant access at either the Application or Channel levels.
  • History: To access historical messages you must grant full read access at either the subscribeKey or channel level. When a user has the appropriate permissions they can access any data stored. If they do not have access a 403 will be returned by PAM.
  • Presence: To grant access to Presence for a particular channel name you must also allow read and write access to the presence channel name which is specified by adding the -pnpres suffix to the name. Also note that a leave will fail in the case where a user's grant expires while connected. An HTTP 403 will be returned.
  • APNS: Standard permissions are required for publishing.
The duration of permission set with grant() are controlled by setting a time-to-live(ttl). If a ttl is not specified it is automatically set to 1440 minutes by default. Once the ttl associated with an entry in PAM has expired, the read and write attributes are immediately set to false for that entry in the PAM table.
 
PAM grant or revoke requests must be less than ~32KB at a time, or the client will return an error. For requests greater than 32KB, break them into smaller batched requests.
 
When the message size exceeds 32KB the server returns the HTTP Error code 500, instead of the correct error code 414.
 
When you init with secretKey, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.
To Grant Permissions on a Channel you can use the following method(s) in the JavaScript V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    Operation ArgumentsHashYesA hash of arguments.
    channels Array Specifying either channels or channelGroups is mandatory.Specifies channels name to grant permissions to. If channels is not specified, the grant applies to all channels associated with the subscribeKey. If auth Key is not specified, it is possible to grant permissions to multiple channels simultaneously by specifying the channels as a comma separated list.
    channelGroups ArraySpecifying either channels or channelGroups is mandatory.Specifies the channelGroups to grant permissions to.
    authKeysArray OptionalSpecifies auth Key to grant permissions to. It is possible to specify multiple auth keys as comma separated list in combination with a single channel name.
    ttl Number Yes1440 (24hrs)Time in minutes for which granted permissions are valid. Default is 1440 (24hrs), Max is 525600 , Min is 1. Setting ttl to 0 will apply the grant indefinitely.
    read Boolean Yesfalse Read permissions are granted by setting to true. Read permissions are removed by setting to false.
    write Boolean Yes falseWrite permissions are granted by setting to true. Write permissions are removed by setting to false.
    manageBooleanYesfalseManage permissions are granted by setting to true. Manage permissions are removed by setting to false.
    callbackFunctionOptionalExecutes on a successful/unsuccessful grant.
pubnub.grant(
    {
        channels: [ch1, ch2],
        channelGroups: [cg1, cg2],
        authKeys: [key1, key2],
        ttl: 12313, // 0 for infinite
        read: true, // false to disallow
        write: true, // false to disallow
        manage: true // false to disallow
    },
    function (status) {
        // handle state setting response
    }
);
  1. // grant world read access to all channels
    
    pubnub.grant({
        read: true
    });
    
  2. pubnub.grant(
        {
            channels: ['my_channel'],
            read: true, // false to disallow
            write: true // false to disallow
        },
        function (status) {
            // handle state setting response
        }
    );
  3. pubnub.grant(
        {
            channels: ['my_channel'],
            authKeys: ['my_ro_authkey'],
            ttl: 5, // 0 for infinite
            read: true, // false to disallow
            write: false // false to disallow
        }, 
        function (status) {
            // handle state setting response
        }
    );
    The above code would return the following response to the client:
    {
    	"status" : 200,
    	"message" : "Success",
    	"payload" : {
    		"ttl" : 5,
    		"auths" : {
    			"my_ro_authkey" : {
    				"r" : 1,
    				"w" : 0
    			}
    		},
    		"subscribe_key" : "my_subkey",
    		"level" : "user",
    		"channel" : "my_channel"
    	},
    	"service" : "Access Manager"
    }
    
  4. pubnub.grant(
        {
            channels: ['my_channel-pnpres'],
            ttl: 5, // 0 for infinite
            read: true, // false to disallow
            write: true // false to disallow
        }, 
        function (status) {
            // handle state setting response
        }
    );
  5. To perform a first level wildcard grant for channel groups you need to specifying : (colon) as the parameter for channelGroups. This will ensure that users can read or manage all channel groups.
    pubnub.grant(
        {
            channelGroups: [':'],
            read: true, 
            manage: true
        }, 
        function (status) {
            // handle state setting response
        }
    );
This function adds a channel to a channel group.
Adding Channels is accomplished by using the following method(s) in the JavaScript V4 SDK:
  1. ParameterTypeRequiredDescription
    Operation ArgumentsHashYesA hash of arguments.
    channelsArrayYesThe channel to add to the channel group.
    channelGroup StringYesThe channelGroup to add the channels to.
    callbackFunctionOptionalExecutes on a successful/unsuccessful addChannels.
pubnub.channelGroups.addChannels(
    {
        channels: ['ch1', 'ch2'],
        channelGroup: "myChannelGroup"
    }, 
    function(status) {
        if (status.error) {
            console.log("operation failed w/ status: ", status);
        } else {
            console.log("operation done!")
        }
    }
);
This function lists all the channels of the channel group.
Listing Channels is accomplished by using the following method(s) in the JavaScript V4 SDK:
  1. ParameterTypeRequiredDescription
    Operation ArgumentsHashYesA hash of arguments.
    channelGroup StringYesChannel Group to list the channel(s) of.
    callbackFunctionOptionalExecutes on a successful/unsuccessful listChannels.
// assuming an intialized PubNub instance already exists
pubnub.channelGroups.listChannels(
    {
        channelGroup: "myChannelGroup"
    }, 
    function (status, response) {
		if (status.error) {
			console.log("operation failed w/ error:", status);
			return;
		}
		
		console.log("listing push channel for device")
		response.channels.forEach( function (channel) {
			console.log(channel)
		})
    }
);

type ListChannelsResponse = {
    channels: Array<string>
}

This function removes the channels from the channel group.
Removing Channels is accomplished by using the following method(s) in the JavaScript V4 SDK:
  1. ParameterTypeRequiredDescription
    Operation ArgumentsHashYesA hash of arguments.
    channelsArrayYesThe channel to remove from the channel group.
    channelGroup StringYesThe channelGroup to remove the channels from.
    callbackFunctionOptionalExecutes on a successful/unsuccessful removeChannels.
// assuming an initialized PubNub instance already exists
pubnub.channelGroups.removeChannels(
    {
        channels: ['son'],
        channelGroup: "family"
    },
    function (status) {
		if (status.error) {
			console.log("operation failed w/ error:", status);
        } else {
            console.log("operation done!")
        }
    }
);
This function removes the channel group.
Deleting Channel Group is accomplished by using the following method(s) in the JavaScript V4 SDK:
  1. ParameterTypeRequiredDescription
    Operation ArgumentsHashYesA hash of arguments.
    channelGroup StringYesThe channelGroup to remove.
    callbackFunctionOptionalExecutes on a successful/unsuccessful deleteGroup.
pubnub.channelGroups.deleteGroup(
    {
        channelGroup: "family"
    },
    function (status) {
        if (status.error) {
            console.log("operation failed w/ error:", status);
        } else {
            console.log("operation done!")
        }
    }
);
This function fetches historical messages of a channel.
PubNub Storage/Playback Service provides real-time access to an unlimited history for all messages published to PubNub. Stored messages are replicated across multiple availability zones in several geographical data center locations. Stored messages can be encrypted with AES-256 message encryption ensuring that they are not readable while stored on PubNub's network.
It is possible to control how messages are returned and in what order, for example you can:
  • Search for messages starting on the newest end of the timeline (default behavior - reverse = false)
  • Search for messages from the oldest end of the timeline by setting reverse to true.
  • Page through results by providing a start OR end time token.
  • Retrieve a slice of the time line by providing both a start AND end time token.
  • Limit the number of messages to a specific quantity using the count parameter.
 
Start & End parameter usage clarity:
If only the start parameter is specified (without end), you will receive messages that are older than and up to that start timetoken value.
If only the end parameter is specified (without start) you will receive messages that match that end timetoken value and newer.
Specifying values for both start and end parameters will return messages between those timetoken values (inclusive on the end value).
Keep in mind that you will still receive a maximum of 100 messages even if there are more messages that meet the timetoken values. Iterative calls to history adjusting the start timetoken is necessary to page through the full set of results if more than 100 messages meet the timetoken values.
To run History you can use the following method(s) in the JavaScript V4 SDK
  1. ParameterTypeRequiredDefaultsDescription
    Operation ArgumentsHashYesA hash of arguments.
    channel StringYesSpecifies channel to return history messages from.
    reverse Boolean Optionalfalse

    Setting to true will traverse the time line in reverse starting with the oldest message first.


    If both start and end arguments are provided, reverse is ignored and messages are returned starting with the newest message.

    count Number Optional100Specifies the number of historical messages to return.

    Default/Maximum is 100.
    stringifiedTimeToken Boolean OptionalfalseIf stringifiedTimeToken is specified as true, the SDK will return timetoken values as a strings instead of integers. Usage of setting is encouraged in javascript environments which perform round-up/down on large integers.
    start String OptionalTime token delimiting the start of time slice (exclusive) to pull messages from.
    end String OptionalTime token delimiting the end of time slice (inclusive) to pull messages from.
    callbackFunctionOptionalExecutes on a successful/unsuccessful history.
Retrieve the last 100 messages on a channel:
pubnub.history(
    {
        channel: 'history_channel',
        reverse: true, // Setting to true will traverse the time line in reverse starting with the oldest message first.
        count: 100, // how many items to fetch
        stringifiedTimeToken: true, // false is the default
        start: '123123123123', // start time token to fetch
        end: '123123123133' // end timetoken to fetch
    },
    function (status, response) {
        // handle status, response
    }
);
type HistoryItem = {
    timetoken: number | string,
    entry: any,
}

type HistoryResponse = {
    messages: Array<HistoryItem>,
    startTimeToken: number,
    endTimeToken: number,
}
  1. pubnub.history(
        {
            channel: 'my_channel',
            reverse: true, // Setting to true will traverse the time line in reverse starting with the oldest message first.
            count: 3, // how many items to fetch
            stringifiedTimeToken: true // false is the default
        },
        function (status, response) {
            // handle status, response
        }
    );
  2. pubnub.history(
        {
            channel: 'my_channel',
            reverse: true, // Setting to true will traverse the time line in reverse starting with the oldest message first.
            stringifiedTimeToken: true, // false is the default
            start: '13406746780720711' // start time token to fetch
        },
        function (status, response) {
            // handle status, response
        }
    );
  3. pubnub.history(
        {
            channel: 'my_channel',
            stringifiedTimeToken: true, // false is the default
            end: '13406746780720711' // start time token to fetch
        },
        function (status, response) {
            // handle status, response
        }
    );
  4.  
    Usage!
    You can call the method by passing 0 or a valid time token as the argument.
    getAllMessages = function(timetoken) {
        pubnub.history(
            {
                channel: 'history_test',
                stringifiedTimeToken: true, // false is the default
                start: timetoken // start time token to fetch
            },
            function (status, response) {
                var msgs = response.messages;
                var start = response.startTimeToken;
                var end = response.endTimeToken;
                // if msgs were retrieved, do something useful with them
                if (msgs != undefined && msgs.length > 0) {
                    console.log(msgs.length);
                    console.log("start : " + start);
                    console.log("end : " + end);
                }
                // if 100 msgs were retrieved, there might be more; call history again
                if (msgs.length == 100)
                    getAllMessages(start);
            }
        );
    }
    
    
    //Usage examples:
    //getAllMessages();
    //getAllMessages(null);
  5. pubnub.history({
        channel: 'history_channel',
        reverse: true, // Setting to true will traverse the time line in reverse starting with the oldest message first.
        count: 100, // how many items to fetch
        stringifiedTimeToken: true, // false is the default
        start: '123123123123', // start time token to fetch
        end: '123123123133' // end timetoken to fetch
    }).then((response) => { 
        console.log(response) 
    }).catch((error) => { 
        console.log(error) 
    });
  6. pubnub.history({
        channel: 'my_channel',
        reverse: true, // Setting to true will traverse the time line in reverse starting with the oldest message first.
        count: 3, // how many items to fetch
        stringifiedTimeToken: true // false is the default
    }).then((response) => { 
        console.log(response) 
    }).catch((error) => { 
        console.log(error) 
    });
  7. pubnub.history({
        channel: 'my_channel',
        reverse: true, // Setting to true will traverse the time line in reverse starting with the oldest message first.
        stringifiedTimeToken: true, // false is the default
        start: '13406746780720711' // start time token to fetch
    }).then((response) => { 
        console.log(response) 
    }).catch((error) => { 
        console.log(error) 
    });
  8. pubnub.history({
        channel: 'my_channel',
        stringifiedTimeToken: true, // false is the default
        end: '13406746780720711' // start time token to fetch
    }).then((response) => { 
        console.log(response) 
    }).catch((error) => { 
        console.log(error) 
    });
  9. getAllMessages = function(timetoken) {
        pubnub.history({
            channel: 'history_test',
            stringifiedTimeToken: true, // false is the default
            start: timetoken // start time token to fetch
        }).then((response) => { 
            console.log(response) 
        }).catch((error) => { 
            console.log(error) 
        });
    }
    
    
    //Usage examples:
    //getAllMessages();
    //getAllMessages(null);
Enable push notifications on provided set of channels.
To run Adding Device to Channel you can use the following method(s) in the JavaScript V4 SDK
  1. ParameterTypeRequiredDescription
    Operation ArgumentsHashYesA hash of arguments.
    channelsArrayYesSpecifies channel to associate with push notifications.
    deviceStringYesThe device id to associate with push notifications.
    pushGateway StringYesapns, mpns or gcm.
    callbackFunctionOptionalExecutes on a successful/unsuccessful addChannels.
pubnub.push.addChannels(
    {
        channels: ['a', 'b'],
        device: 'niceDevice',
        pushGateway: 'apns' // apns, gcm, mpns
    },
    function(status) {
        if (status.error) {
            console.log("operation failed w/ error:", status);
        } else {
            console.log("operation done!")
        }
    }
);
[1, "Modified Channels"]
Request for all channels on which push notification has been enabled using specified pushToken.
To run Listing Channels For Device you can use the following method(s) in the JavaScript V4 SDK
  1. ParameterTypeRequiredDescription
    Operation ArgumentsHashYesA hash of arguments.
    deviceStringYesThe device id to associate with push notifications.
    pushGateway StringYesapns, mpns or gcm.
    callbackFunctionOptionalExecutes on a successful/unsuccessful listChannels.
pubnub.push.listChannels(
    {
        device: 'niceDevice',
        pushGateway: 'apns' // apns, gcm, mpns
    },
    function (status, response) { 
        if (status.error) { 
            console.log("operation failed w/ error:", status);
            return;
        }

        console.log("listing push channel for device")
        response.channels.forEach( function (channel) {
            console.log(channel)
        })
    }
);
type ListPushChannelsResponse = {
    channels: Array<string>
}
Disable push notifications on provided set of channels. If nil will be passed as channels then client will remove push notifications from all channels which associated with pushToken.
To run Removing Device From Channel you can use the following method(s) in the JavaScript V4 SDK
  1. ParameterTypeRequiredDescription
    Operation ArgumentsHashYesA hash of arguments.
    channelsArrayYesSpecifies channel to associate with push notifications.
    deviceStringYesThe device id to associate with push notifications.
    pushGateway StringYesapns, mpns or gcm.
    callbackFunctionOptionalExecutes on a successful/unsuccessful removeChannels.
pubnub.push.removeChannels(
    {
        channels: ['a', 'b'], 
        device: 'niceDevice', 
        pushGateway: 'apns' // apns, gcm, mpns
    },
    function(status) {
        if (status.error) {
            console.log("operation failed w/ error:", status);
        } else {
            console.log("operation done!")
        }
    }
);
The output below demonstrates the response to a successful call:
[1, "Modified Channels"]
Disable push notifications from all channels which is registered with specified pushToken.
To run Remove all push notifications you can use the following method(s) in the JavaScript V4 SDK
  1. ParameterTypeRequiredDescription
    Operation ArgumentsHashYesA hash of arguments.
    deviceStringYesThe device id to associate with push notifications.
    pushGateway StringYesapns, mpns or gcm.
    callbackFunctionOptionalExecutes on a successful/unsuccessful deleteDevice.
pubnub.push.deleteDevice(
    {
        device: 'niceDevice', 
        pushGateway: 'apns' // apns, gcm, mpns
    }, 
    function (status) {
        if (status.error) {
            console.log("operation failed w/ error:", status);
        } else {
            console.log("operation done!")
        }
    }
);
The server responds with a status code of 200.
End all open requests and close PubNub instance.
pubnub.stop();
This function allow to decrypt the data.
To decrypt the data you can use the following method(s) in JavaScript V4 SDK.
  1. ParameterTypeRequiredDescription
    dataObjectYesThe data to decrypt.
    customCipherKeyStringOptionalIf it's not provided, the cipher key from config will be used.
This function allow to encrypt the data.
To encrypt the data you can use the following method(s) in JavaScript V4 SDK.
  1. ParameterTypeRequiredDescription
    dataStringYesThe data to encrypt.
    customCipherKeyStringOptionalIf it's not provided, the cipher key from config will be used.
Call the reconnect method to force the SDK to try and reach out PubNub.
To reconnect the data you can use the following method(s) in JavaScript V4 SDK.
  1. This method doesn't take any arguments.
pubnub.reconnect();
This function will return a 17 digit precision Unix epoch.
 
Timetoken
The timetoken is constructed using the following algorithm:
timetoken = (Unix epoch time in seconds) * 10000000
Example of creating a timetoken for a specific time & date
08/19/2013 @ 9:20pm in UTC = 1376961606
timetoken = 1376961606 * 10000000
timetoken = 13769616060000000
To fetch Time you can use the following method(s) in JavaScript V4 SDK
  1. ParameterTypeRequiredDescription
    callback Function YesCallback is called after a successful return.
// assuming an intialized PubNub instance already exists
pubnub.time(function(status, response) {
	if (status.error) {
		// handle error if something went wrong based on the status object
	} else {
		console.log(response.timetoken)
	}
})
type TimeResponse = {
    timetoken: number
};
  1. pubnub.time().then((timetoken) => {
        console.log(timetoken);
    }).catch((error) => {
        console.log(error)
    });
Check out PubNub's other JavaScript-based SDKs, such as JavaScript V4, Node.js V4.