Feedback

WebWebNode.jsReact NativePhoneGapJavaScriptPubNub JavaScript V4 SDK 4.5.0

 

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.




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

<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.5.0.js"></script>
function publish() {
  
    pubnub = new PubNub({
        publishKey : 'demo',
        subscribeKey : 'demo'
    })
      
    function publishSampleMessage() {
        console.log("Since we're publishing on subscribe connectEvent, we're sure we'll receive the following publish.");
        var publishConfig = {
            channel : "hello_world",
            message : "Hello from PubNub Docs!"
        }
        pubnub.publish(publishConfig, function(status, response) {
            console.log(status, response);
        })
    }
      
    pubnub.addListener({
        status: function(statusEvent) {
            if (statusEvent.category === "PNConnectedCategory") {
                publishSampleMessage();
            }
        },
        message: function(message) {
            console.log("New Message!!", message);
        },
        presence: function(presenceEvent) {
            // handle presence
        }
    })      
    console.log("Subscribing..");
    pubnub.subscribe({
        channels: ['hello_world'] 
    });
};
In addition to the Hello World sample code, we also provide some copy and paste snippets of common API functions:
Instantiate a new Pubnub instance. Only the subscribeKey is mandatory. Also include publishKey if you intend to publish from this instance, and the secretKey if you wish to perform PAM administrative operations from this JavaScript V4 instance.
 
It is not a best practice to include the secretKey in client-side code for security reasons.
 
Set restore as true to allow catch up on the front-end applications.
var pubnub = new PubNub({
	subscribeKey: "mySubscribeKey",
	publishKey: "myPublishKey",
	ssl: true
})
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 publishTime = p.timestamp; // Publish timetoken
        var timetoken = p.timetoken;  // Current timetoken
        var uuid = p.uuid; // UUIDs of users who are connected with the channel
    },
    status: function(s) {
        // handle status
    }
})
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).
Call time() to verify the client connectivity to the origin:
// 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)
	}
})
pubnub.subscribe({
    channels: ['my_channel'],
    withPresence: true // also subscribe to presence instances.
})
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.
Publish a message to a channel:
pubnub.publish(
    {
        message: {
            such: 'object'
        },
        channel: 'ch1',
        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) {
        // handle status, response
    }
);
Get occupancy of who's here now on the channel by UUID:
Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
pubnub.hereNow(
    {
        channels: ["ch1"], 
        channelGroups : ["cg1"],
        includeUUIDs: true,
        includeState: true 
    },
    function (status, response) {
        // handle status, response
    }
);
Subscribe to realtime Presence events, such as join, leave, and timeout, by UUID. Setting the presence attribute to a callback will subscribe to presents events on my_channel:
Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
pubnub.subscribe({
	channels: ['my_channel_1', 'my_channel_2', 'my_channel_3'],
	withPresence: true
})
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.
Retrieve published messages from archival storage:
Requires that the Storage and Playback add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
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
    }
);
pubnub.unsubscribe({
    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.
Check out PubNub's other JavaScript-based SDKs, such as JavaScript V4, Node.js V4.