First, we will build a simple UI for demonstration of the chat application. We are providing two options as ‘Chat with user1’ and ‘Chat with user2’.
<a href="javascript:activateUser(2)">Chat with user 1</a> <a href="javascript:activateUser(1)">Chat with user 2</a>
When you select ‘Chat with user1’ option, you will be logged in as ‘user2’. The chat window at the bottom right will be open where you can receive messages for ‘user2’ and send messages to ‘user1’.
On the other side, when you choose option 2 i.e. ‘Chat with user2’, you will be logged in as ‘user1’. The chat window at the bottom right will be open where you can receive messages for ‘user1’ and send messages to ‘user2’.
Open the tutorial link in two different browsers and login as two different users by choosing one of the above two options.
Now ‘user1’ and ‘user2’ can chat with each other. As you refresh your browser or close the chat window, you will be logged out and will no longer be able to receive messages.
This is the basic workflow of the application. Now we will see how it actually works.
For using Pusheo JavaScript API, you just need to include pusheo.js file in your application.
// Pusheo JavaScript API <script type="text/javascript" src="javascript/pusheo.js"></script>
You also need to include your application Javascript and css files.
// Application Javascript and css files <link rel="stylesheet" type="text/css" href="css/sampleChat.css" /> <script type="text/javascript" src="javascript/jQuery-1.10.2.js"></script> <script type="text/javascript" src="javascript/sampleChat.js"></script>
In sampleChat.js we have declared three variables as:
// sampleChat.js three variables var pusheo; var sender; var receiver;
‘sender’ will be used to identify the subscribed user (‘user1’ or ‘user2’), ‘receiver’ will represent the receiving user and ‘pusheo’ is used as Pusheo object. Using this object, we can use the different Pusheo features.
As mentioned above, we are providing two options as ‘Chat with user1’ and ‘Chat with user2’.
<a href="javascript:activateUser(2)">Chat with user 1</a> <a href="javascript:activateUser(1)">Chat with user 2</a>
As you click on any of the above options, the following Javascript function in sampleChat.js will be invoked.
function activateUser(flag){ $('#chatBox').show(); $('.user').hide(); if(flag==1) { sender='user1'; receiver='user2'; $('.chatHead').append('User 2'); $('.chatHead').append('<div class='chatOptions'><a href='javascript:minimize()'>-</a><a href='javascript:unsubscribeUser()'>X</a></div>'); $('.loginMessage').append('You have logged in as User 1'); } else if(flag==2){ sender='user2'; receiver='user1'; $('.chatHead').append('User 1'); $('.chatHead').append('<div class='chatOptions'><a href='javascript:minimize()'>-</a><a href='javascript:unsubscribeUser()'>X</a></div>'); $('.loginMessage').append('You have logged in as User 2'); } subscribeUser(); }
In this function, we are passing a parameter as ‘flag’.
‘flag=1’ indicates sender is ‘user1’ and receiver is ‘user2’. So you will be subscribed as ‘user1’. Vice versa, ‘flag=2’ indicates sender is ‘user2’ and receiver is ‘user1’. So you will be subscribed as ‘user2’.
The chat window at the bottom-right will be visible for the respective users.
We are internally calling ‘subscribeUser’ function within this function.
Function ‘subscribeUser()’ will initialize Pusheo object (i.e ‘var pusheo’) as follows:
function subscribeUser(){ /* Initialize Pusheo object */ pusheo = new Pusheo({ publish_key: 'demo', subscribe_key: 'demo', url: http://localhost:8080/ }); /* Subscibe to channel identified by sender using this object*/ pusheo.subscribe({ channel: sender, lost_messages_call: false, open: onOpen, message: onMessage, message_sent: onMessageSent, close: onClose, error: onError, }); }
Here, for initializing ‘pusheo object’, you need to provide valid pair of ‘publish_key’ and ‘subscribe_key’. Also, you need to specify serverUrl.
After initializing ‘pusheo object’, you can subscribe to a channel. For this, you need to call ‘subscribe’ function using ‘pusheo object’. Here, channel name will be your sender name (either ‘user1’ or ‘user2’).
After completion of this step, you will be able to receive and send messages using your subscribed channel. Now while subscribing, we have specified callback functions as onOpen, onMessage, onMessageSent, onClose and onError.
In the next step, we will see how to implement these functions.
You need to define all callback functions in your javascript (sampleChat.js) that you have mentioned while subscribing to a channel as follows:
function onOpen(response) { console.log("opened"); } function onMessage(response) { $(".chatContent").append("<div class="message"><b>"+receiver+" : </b>"+response+"</div>"); $(".chatContent").scrollTop($(".chatContent")[0].scrollHeight); } function onMessageSent(response) { console.log("message sent "); } function onClose(response) { console.log("closed"); } function onError(response) { console.log("Error"); }
These functions represent the lifecycle of the connection. For more details, refer API documentation.
In ‘onMessage()’ function, we are just appending a message in the chat window that the current subscribed channel is receiving.
Now for sending messages, you just need to type your message in text area of the chat window and press ‘Enter’. As you press ‘Enter’, the following function defined in ‘sampleChat.js’ will be invoked:
$('.textArea').keydown(function(e) { if(e.which == 13) { e.preventDefault(); var msg=$('.textArea').val(); if(msg.length!==0) { $('.chatContent').append('<div class='message'><b>'+sender+' : </b>'+msg+'</div>'); $('.chatContent').scrollTop($('.chatContent')[0].scrollHeight); pusheo.publish({ channel: receiver, message: msg }); } $('.textArea').val(''); } });
Here, using ‘Pusheo object’, you can publish messages to the user. You just need to call the ‘publish’ method using this object and specify the channel i.e. who will be receiving the message. In our case, the variable ‘receiver’ will be the receiving channel and ‘message’ is the text that you have entered in the text area of the chat window.
In case you want to stop receiving messages, you can refresh the browser or click on the ‘X’ option of the chat window. As you click on the ‘X’ option, the following function defined in ‘sampleChat.js’ will be invoked.
function unsubscribeUser(){ pusheo.unsubscribe({ channel: sender }); $('#chatBox').hide(); $('.user').show(); $('.loginMessage').html(''); $('.chatHead').html(''); $('.chatContent').html(''); }
To unsubscribe from channel, you just need to call ‘unsubscribe’ method using pusheo object ‘pusheo’ and pass the channel you wish to unsubscribe from. In our case, channel will be our variable ‘sender’ (logged in user). After this chat window is closed and all contents will be cleared.
The full example is available for download here.