close search

Add Messaging, Voice, and Authentication to your apps with Vonage Communications APIs

Visit the Vonage API Developer Portal

Back to Tutorials

Text Chat Tutorial (Web)


Text chat is implemented using the OpenTok signaling API. A signal is sent using the signal() method of the Session object. To receive a signal a client needs to listen to the signal event dispatched by the session object.

Setting up your project

To follow this tutorial, clone OpenTok's Web sample apps repo on GitHub:

git clone

Then open the Signaling folder in your code editor to follow along.

Exploring the code

In our application, when the user enters text in the input text field, the following code is executed:

form.addEventListener('submit', function(event) {

        type: 'msg',
        data: msgTxt.value
      }, function(error) {
      if (error) {
        console.log('Error sending signal:',, error.message);
      } else {
        msgTxt.value = '';

This method calls the signal() method of the Session object, which sends a signal to all clients connected to the OpenTok session. Each signal is defined by a type property identifying the type of message (in this case "msg") and a data property containing the message. The text entered is sent in the data property of the signal method.

When another client connected to the session (in this app, there is only one) sends a message, the session's signal event handler is invoked:

session.on('signal:msg', function(event) {
  var msg = document.createElement('p');
  msg.innerText =;
  msg.className = event.from.connectionId === session.connection.connectionId ? 'mine' : 'theirs';

This method checks to see if the signal was sent by the local web client or by the other client connected to the session:

event.from.connectionId === session.connection.connectionId ? 'mine' : 'theirs';

The Session object represents your OpenTok session. It has a connection property, which has a connectionId property. The event object represents the event associated with this signal. It has a from property (which is a Connection object) with a connectionId property. This represents the connection ID of the client sending the signal. If these match, the signal was sent by the local web client.

The data associated with the event is then appended as a child of the history DOM element.

This app uses the OpenTok signaling API to implement text chat. However, you can use the signaling API to send messages to other clients (individually or collectively) connected to the session.

Congratulations! You've finished the Text Chat Tutorial for Web.
You can continue to play with and adjust the code you've developed here, or check out the Next Steps below. For more information on signaling, see the OpenTok signaling developer guide.