JavaScriptWebWebNode.jsPhoneGapReactReduxTitaniumVueJavaScript V4 SDK 4.29.2



View Supported Platforms

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


<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.29.2.js"></script>
 Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
function publish() {
  
    pubnub = new PubNub({
        publishKey : 'demo',
        subscribeKey : 'demo',
        uuid: "myUniqueUUID"
    })
      
    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: { 
                title: "greeting",
                description: "hello world!"
            }
        }
        pubnub.publish(publishConfig, function(status, response) {
            console.log(status, response);
        })
    }
      
    pubnub.addListener({
        status: function(statusEvent) {
            if (statusEvent.category === "PNConnectedCategory") {
                publishSampleMessage();
            }
        },
        message: function(msg) {
            console.log(msg.message.title);
            console.log(msg.message.description);
        },
        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.

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.

 
Set restore to true to allow catch-up on front-end applications.
 Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
var pubnub = new PubNub({
	subscribeKey: "mySubscribeKey",
	publishKey: "myPublishKey",
	uuid: "myUniqueUUID",
	ssl: true
})
pubnub.addListener({
  // Messages
  message: function (m) {
    const channelName = m.channel; // Channel on which the message was published
    const channelGroup = m.subscription; // Channel group or wildcard subscription match (if exists)
    const pubTT = m.timetoken; // Publish timetoken
    const msg = m.message; // Message payload
    const publisher = m.publisher; // Message publisher
  },
  // Presence
  presence: function (p) {
    const action = p.action; // Can be join, leave, state-change, or timeout
    const channelName = p.channel; // Channel to which the message belongs
    const occupancy = p.occupancy; // Number of users subscribed to the channel
    const state = p.state; // User state
    const channelGroup = p.subscription; //  Channel group or wildcard subscription match, if any
    const publishTime = p.timestamp; // Publish timetoken
    const timetoken = p.timetoken; // Current timetoken
    const uuid = p.uuid; // UUIDs of users who are subscribed to the channel
  },
  // Signals
  signal: function (s) {
    const channelName = s.channel; // Channel to which the signal belongs
    const channelGroup = s.subscription; // Channel group or wildcard subscription match, if any
    const pubTT = s.timetoken; // Publish timetoken
    const msg = s.message; // Payload
    const publisher = s.publisher; // Message publisher
  },
  objects: (objectEvent) => {
    const channel = objectEvent.channel; // Channel to which the event belongs
    const channelGroup = objectEvent.subscription; // Channel group
    const timetoken = objectEvent.timetoken; // Event timetoken
    const publisher = objectEvent.publisher; // UUID that made the call
    const event = objectEvent.event; // Name of the event that occurred
    const type = objectEvent.type; // Type of the event that occurred
    const data = objectEvent.data; // Data from the event that occurred
  },
  messageAction: function (ma) {
    // handle message action
    const channelName = ma.channel; // Channel to which the message belongs
    const publisher = ma.publisher; // Message publisher
    const event = ma.message.event; // Message action added or removed
    const type = ma.message.data.type; // Message action type
    const value = ma.message.data.value; // Message action value
    const messageTimetoken = ma.message.data.messageTimetoken; // Timetoken of the original message
    const actionTimetoken = ma.message.data.actionTimetoken; // Timetoken of the message action
  },
  file: function (event) {
    const channelName = event.channel; // Channel to which the file belongs
    const channelGroup = event.subscription; // Channel group or wildcard subscription match (if exists)
    const publisher = event.publisher; // File publisher
    const timetoken = event.timetoken; // Event timetoken

    const message = event.message; // Optional message attached to the file
    const fileId = event.file.id; // File unique id
    const fileName = event.file.name;// File name
    const fileUrl = event.file.url; // File direct URL
  },
  status: function (s) {
    const affectedChannelGroups = s.affectedChannelGroups; // Array of channel groups affected in the operation
    const affectedChannels = s.affectedChannels; // Array of channels affected in the operation
    const category = s.category; // Returns PNConnectedCategory
    const operation = s.operation; // Returns PNSubscribeOperation
    const lastTimetoken = s.lastTimetoken; // Last timetoken used in the subscribe request (type long)
    const currentTimetoken = s.currentTimetoken; /* Current timetoken fetched in subscribe response,
                                                * to be used in the next request (type long) */
    const subscribedChannels = s.subscribedChannels; // Array of all currently subscribed channels
  },
});
var existingListener = {
  message: function () {
  },
};

pubnub.removeListener(existingListener);
CategoriesDescription
PNNetworkUpCategoryThe SDK detected that the network is online.
PNNetworkDownCategoryThe SDK announces this when a connection isn't available, or when the SDK isn't able to reach the PubNub Data Stream Network.
PNNetworkIssuesCategoryA subscribe event experienced an exception when running.
The SDK isn't able to reach the PubNub Data Stream Network.
This may be due to many reasons, such as: the machine or device isn't connected to the internet; the internet connection has been lost; your internet service provider is having trouble; or, perhaps the SDK is behind a proxy.
PNReconnectedCategoryThe SDK was able to reconnect to PubNub.
PNConnectedCategorySDK subscribed with a new mix of channels.
This is fired every time the channel or channel group mix changes.
PNAccessDeniedCategoryPAM permission failure.
PNMalformedResponseCategoryJSON parsing crashed.
PNBadRequestCategoryThe server responded with a bad response error because the request is malformed.
PNDecryptionErrorCategoryIf using decryption strategies and the decryption fails.
PNTimeoutCategoryFailure to establish a connection to PubNub due to a timeout.
PNRequestMessageCountExceedCategoryThe SDK announces this error if requestMessageCountThreshold is set, and the number of messages received from PubNub (in-memory cache messages) exceeds the threshold.
PNUnknownCategoryReturned when the subscriber gets a non-200 HTTP response code from the server.
Call time() to verify the client connectivity to the origin:
// assuming an initialized 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'],
});
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 you to enable the Presence add-on for your key. Refer to the How do I enable add-on features for my keys? knowledge base article for details on enabling features.
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 you to enable the Presence add-on for your key. Refer to the How do I enable add-on features for my keys? knowledge base article for details on enabling features.
pubnub.subscribe({
	channels: ['my_channel'],
	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',
        count: 100, // how many items to fetch
        stringifiedTimeToken: true, // false is the default
    },
    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.