JavaScript Quickstart
In this Quickstart, you'll learn in minutes how to build your first web app using JavaScript that sends and receives a message, in addition to learning how to use status and presence events to enhance your realtime application.
Sample app Quickstart | SDK Getting Started |
---|---|
PubNub Account
Sign in or create an account to create an app on the Admin Portal and get the keys to use in this Quickstart.
Download Sample App
You can clone the repository that contains the files we will use in this Quickstart. Remember to replace the publish and subscribe key placeholders with your own keys.
https://github.com/pubnub/javascript-quickstart-platform
Project Setup
To build a JavaScript web app manually:
- Create a project folder on your system named pnquickstart
- Under that project folder, create a file named index.html
Add Project Files
For this Quickstart, we will focus on a bare minimum UI only. Copy the following code and paste it into the index.html
file in your project. We will break it all down for you below.
index.html
<!DOCTYPE html>
<html>
<head>
<title>PubNub JavaScript SDK QuickStart</title>
</head>
<body>
<div>
<strong>Earth:</strong> <input id="update-text" type="input" placeholder="enter update for Earth here"/>
<input id="publish-button" type="submit" value="Submit Update to The Guide"/>
<p><strong>Updates</strong></p>
<div id="messages-top"/>
</div>
<!-- Get PubNub javascript SDK-->
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.27.4.min.js"></script>
<script>
const messagesTop = document.getElementById('messages-top');
const updateText = document.getElementById('update-text');
const sendButton = document.getElementById('publish-button');
sendButton.addEventListener('click', () => {submitUpdate(theEntry, updateText.value)});
const theChannel = 'the_guide';
const theEntry = 'Earth';
const pubnub = new PubNub({
// replace the key placeholders with your own PubNub publish and subscribe keys
publishKey: 'myPublishKey',
subscribeKey: 'mySubscribeKey',
uuid: "ReplaceWithYourClientIdentifier"
});
pubnub.addListener({
message: function(event) {
displayMessage('[MESSAGE: received]',
event.message.entry + ': ' + event.message.update);
},
presence: function(event) {
displayMessage('[PRESENCE: ' + event.action + ']',
'uuid: ' + event.uuid + ', channel: ' + event.channel);
},
status: function(event) {
displayMessage('[STATUS: ' + event.category + ']',
'connected to channels: ' + event.affectedChannels);
if (event.category == 'PNConnectedCategory') {
submitUpdate(theEntry, 'Harmless.');
}
}
});
pubnub.subscribe({
channels: ['the_guide'],
withPresence: true
});
submitUpdate = function(anEntry, anUpdate) {
pubnub.publish({
channel : theChannel,
message : {'entry' : anEntry, 'update' : anUpdate}
},
function(status, response) {
if (status.error) {
console.log(status)
}
else {
displayMessage('[PUBLISH: sent]',
'timetoken: ' + response.timetoken);
}
});
};
displayMessage = function(messageType, aMessage) {
let pmessage = document.createElement('p');
let br = document.createElement('br');
messagesTop.after(pmessage);
pmessage.appendChild(document.createTextNode(messageType));
pmessage.appendChild(br);
pmessage.appendChild(document.createTextNode(aMessage));
}
</script>
</body>
</html>
Replace Pub/Sub Key Placeholders
Remember to replace the myPublishKey and mySubscribeKey placeholders with your own PubNub publish and subscribe keys.
Run the app
1. Open a new browser tab. You should see the browser display something that looks like this: "A message was published on page load and some other messages/events were displayed." 2. Submit a new entry by entering some text and click Submit Update to the Guide button to publish this new update. You should see the new update inserted at the top of the current messages below the button. And the entry update field is cleared for you to enter something new. | ![]() |
Message Display Order
You may see the [MESSAGE: received] appear before the [PUBLISH: sent] message or possibly after, since all this code is executed asynchronously.
Walkthrough
Let's skip the new folder and file creation and review what is happening for all this to work properly.
Include JavaScript SDK
- You included the JavaScript SDK library by using the CDN link
- You added the PubNub SDK to your web application using our CDN link
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.27.4.min.js"></script>
Create the UI
The UI is intentionally simple to reduce the amount of code necessary to bind the message updates to the UI components.
The following adds a text field and button element to your HTML page, and a message area placeholder element where new messages and events are received. It also binds the click
event of the button to execute the submitUpdate
function.
const messagesTop = document.getElementById('messages-top');
const updateText = document.getElementById('update-text');
const sendButton = document.getElementById('publish-button');
sendButton.addEventListener('click', () => {submitUpdate(theEntry, updateText.value)});
Clicking this button triggers the publish
code.
Initialize the PubNub Object
The PubNub object allows you to make PubNub API calls, like publish
, subscribe
and more. There are more configuration properties than what you see here, but this is all you need for this Quickstart. Of course, you would use your own publish/subscribe keys below.
It's important to set the uuid
for the client. This is typically received from your server after the client logs in successfully.
Successive App Run Behavior
If you test run the app multiple times within a few minutes, you may not see the presence join event appear because the client's UUID is the same as the previous run and is still considered active from the previous run.
const pubnub = new PubNub({
publishKey: "myPublishKey",
subscribeKey: "mySubscribeKey",
uuid: "ReplaceWithYourClientIdentifier"
});
Proper PubNub Initialization
If your app has several views that require the PubNub object, then you can initialize it in the initial view of your app and pass from one view to another. However, if PubNub is only required in seldom used sections of your app, you might just initialize it on demand in that view. You may implement other common strategies for building your UIs and passing data.
Listening for Messages & Events
This addListener
code has event handler functions where all published messages and other events are received. For this app, you're only interested in the message
, status
and presence
handlers. There are several other handlers you can use for other features of PubNub.
- The
message
handler receives all messages published to all channels subscribed by this client. When a message is received, you're simply appending the content to the bottom of the web page. - The
presence
handler receives all presence events for the channels subscribed by this client. You'll only see thejoin
event of this client unless you open a second client (in a different browser or incognito window) - The
status
handler allows you to monitor and manage the connection. You'll see aPNConnectedCategory
event for when the client subscribes to the channel. This event triggers the initialpublish
.
pubnub.addListener({
// handlers go here
});
Receiving Messages
The message
handler receives all messages published to all channels subscribed by this client. When a message is received, you're simply appending the message above the existing messages.
message: function(event) {
displayMessage('[MESSAGE: received]',
event.message.entry + ': ' + event.message.update);
}
Receiving Status Events
The status
handler allows you to monitor and manage the connection to the PubNub Platform and channels. When the client subscribes to a channel, a PNConnectedCategory
status event will be received to indicate a successful channel connection. You're using this event to submit an initial entry update (publishing a message to a channel).
status: function(event) {
displayMessage('[STATUS: ' + event.category + ']',
'connected to channels: ' + event.affectedChannels);
if (event.category == 'PNConnectedCategory') {
submitUpdate(theEntry, 'Harmless.');
}
}
Receiving Presence Events
The presence
handler allows you to monitor when this and other clients join and leave channels. The subscribe
call includes a withPresence
parameter that indicates that the client wishes to receive presence events on the subscribed channels. In this app, you'll only receive a join
event. If you were to execute the app using another client (like the PubNub Dev Console), you would see a join
event for that client, too. You would also see leave
events when the other clients unsubscribe from a channel or a timeout
event if they go offline without first unsubscribing.
presence: function(event) {
displayMessage('[PRESENCE: ' + event.action + ']',
'uuid: ' + event.uuid + ', channel: ' + event.channel);
}
Subscribing to Channels
This subscribe
opens a connection to PubNub and waits for messages to be publish
-ed to this channel. You can subscribe to more than one channel at a time but you only need one for this Quickstart. The withPresence:true
method enables presence events to be sent for the channel being subscribed in this call.
pubnub.subscribe({
channels: ['the_guide'],
withPresence: true
});
Publishing Messages
The submitUpdate
method is invoked when you click the Submit Update to the Guide button. This method wraps the publish
API so that you can call it from anywhere in the Activity in a standard way.
The messages that publish to this channel are received by this and other clients subscribed to this channel in the message
handler. The success of a publish
is updated in the message UI component with the publish timetoken
value.
submitUpdate = function(anEntry, anUpdate) {
pubnub.publish({
channel : theChannel,
message : {'entry' : anEntry, 'update' : anUpdate}
},
function(status, response) {
if (status.error) {
console.log(status)
}
else {
displayMessage('[PUBLISH: sent]',
'timetoken: ' + response.timetoken);
updateText.value="";
}
});
};
Displaying Messages
The displayMessage
method is a single place where all updates to the messages UI component are handled in a standard way. Anytime a new message or event needs to be displayed, it's prepended to the existing messages so that the latest update is always at the top.
In a real world app, you would have more sophisticated data binding using a list or table element that leverages an MVC framework, like React or Angular.
Anytime you need to update the UI, you call the displayMessage
function.
displayMessage = function(messageType, aMessage) {
let pmessage = document.createElement('p');
let br = document.createElement('br');
messagesTop.after(pmessage);
pmessage.appendChild(document.createTextNode(messageType));
pmessage.appendChild(br);
pmessage.appendChild(document.createTextNode(aMessage));
}
Next Steps
Now that you have your JavaScript Web app up and running with PubNub, learn more about what else you can do with Channels. To discover what else our JavaScript SDK offers, go to our SDK Reference docs for JavaScript.