close search

Back to Text Chat Overview

Text Chat Step 1: Adding text chat

Using the signaling API to implement text chat

To see the code for this sample, switch to the signaling branch of the learning-opentok-web repo:

git checkout signaling

This page shows the difference between this branch and the basics branch which it was built upon.

The code in the signaling branch builds on the code from the basics branch. Here is the added code: diff.

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.

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.