Suggestions

close search

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

Visit the Vonage API Developer Portal

Joining a Session — Web

Using a session ID and token, you can connect to the OpenTok session using the OpenTok.js library.

This topic includes the following sections:

For information on creating a session ID and an authentication token, see Session Creation and Token Creation.

Initializing a Session object

Before you can connect to a session, instantiate a Session object by calling the OT.initSession() method with your OpenTok API key and the appropriate session ID:

// Replace with your OpenTok API key and session ID:
var session = OT.initSession(apiKey, sessionID);

The OT.initSession() method returns a Session object, through which subsequent API calls take place.

Note that calling the OT.initSession() method does not create an OpenTok session; it creates a JavaScript Session object, which represents an existing OpenTok session. You create an OpenTok session using the OpenTok server-side libraries. See Creating an OpenTok session.

If the user's browser does not support WebRTC, the call to OT.initSession() results in the page displaying a message to the user. To check for WebRTC support and prevent this message from being displayed, you can call the OT.checkSystemRequirements() method before calling OT.initSession():

if (OT.checkSystemRequirements() == 1) {
  var session = OT.initSession(apiKey, sessionId);
} else {
  // The client does not support WebRTC.
  // You can display your own message.
}

Connecting to a session

Once you have initialized a Session object, call its connect() method, passing in a token and a completion handler function:

var session = OT.initSession(apiKey, sessionId);
session.connect(token, function(error) {
  if (error) {
    console.log("Error connecting: ", error.name, error.message);
  } else {
    console.log("Connected to the session.");
  }
});

An error object is passed into the completion handler of the connect event when the client fails to connect to the OpenTok session. Otherwise, no error object is passed in, indicating that the client connected successfully to the session.

The Session object also dispatches a sessionConnected event when the client connects to the OpenTok session. And the OT object dispatches an exception event when there is an error in connecting. However, it is simpler to check for success in connecting by passing a completion handler into the connect() method, as the last parameter.

Disconnecting from a session

To disconnect from a session, call the disconnect() method of the Session object:

session.disconnect();

Detecting when you have disconnected

When your client disconnects from a session, the Session object dispatches a sessionDisconnected event:

session.on("sessionDisconnected", function (event) {
  // The event is defined by the SessionDisconnectEvent class
  if (event.reason == "networkDisconnected") {
    alert("Your network connection terminated.")
  }
});
session.connect(token);

The reason property of the event is a string that describes why the session disconnected. For example, the previous example notifies the user if they were disconnected due to the network connection terminating. For details, see SessionDisconnectEvent.

Automatic reconnection

Clients will attempt to automatically reconnect to a session they disconnect unexpectedly (for example, due to a drop in network connectivity). You do not need to add any code to have the clients reconnect automatically, unless you want to respond to events dispatched when your client disconnects and reconnects. For sample code that demonstrates the use of these events, see the opentok-reconnection repo on GitHub.

When the connection is dropped and the client tries to reconnect, the Session object dispatches a reconnecting event. When the connection is restored, the Session object dispatches a reconnected event. If the client cannot restore the connection, the client disconnects from the OpenTok session, and the Session object dispatches the sessionDisconnected event.

In response to these events, your application can (optionally) display user interface notifications indicating the temporary disconnection, reconnection, and disconnection states:

session.on(
  sessionReconnecting: function() {
    // Display a user interface notification.
  },
  sessionReconnected: function() {
    // Adjust user interface.
  },
  sessionDisconnected: function() {
    // Adjust user interface.
  }
);

When your client temporarily disconnects from a session, the Subscriber objects in clients subscribing to a stream you publish dispatch events when your published stream drops and when (and if) it resumes automatically. For more information, see Automatic reconnection in the "Subscribing to streams" developer guide.

By default, any signals you send while your client is temporarily disconnected from a session are queued and sent when (and if) you successfully reconnect. You can set the retryAfterReconnect property to false in the options you pass into the Session.signal() method to prevent signals from being queued while you are disconnected. For more information, see Preventing signals from being sent during automatic reconnection.

Detecting when clients have connected and disconnected

The Session object dispatches a connectionCreated event when a new client (including your own) connects to the session. The Session object dispatches a connectionDestroyed event when other clients leave the session. These events are defined by the ConnectionEvent class, which has a connection object, which is a Connection object for the connection (created or destroyed) related to the event:

var connectionCount;
session.on({
  connectionCreated: function (event) {
    connectionCount++;
    if (event.connection.connectionId != session.connection.connectionId) {
      console.log('Another client connected. ' + connectionCount + ' total.');
    }
  },
  connectionDestroyed: function connectionDestroyedHandler(event) {
    connectionCount--;
    console.log('A client disconnected. ' + connectionCount + ' total.');
  }
});
session.connect(token, function (error) {
  if (error) {
    console.log("Failed to connect.");
  } else {
    console.log('You have connected to the session.');
  }
});

Troubleshooting session connection issues

The Session.connect() method has a callback function which is passed an optional error parameter. If this parameter is present and defined (not null or undefined), then there was an error when connecting. Looking for this error in your code will help you decipher why the end-user was unable to connect:

session.connect(token, function(err) {
  if (err) {
    // handle error
  } else {
    // connection succeeded
  }
});

A large number of errors that come back when attempting to connect are due to either invalid or expired tokens. Make sure you are following the token best practices outlined here.

Another common reason for connecting to a session failing is due to the end user's internet connection. Examples of this include:

This will result in an error with the code 1006. We recommend you handle this using the code below. Other reasons for connecting to a session failing include the OpenTok servers being down, or that some kind of unexpected error happened (such as a 500-level error in the server). While this doesn't happen often, it is good practice to handle these errors.

If you follow these instructions your error handling code should look something like:

session.connect(token, function(err) {
  if (err) {
    if (err.name === "OT_NOT_CONNECTED") {
      showMessage('Failed to connect. Please check your connection and try connecting again.');
    } else {
      showMessage('An unknown error occurred connecting. Please try again later.');
    }
  }
});

You can lose your connection after you have already successfully connected to a Session. You can handle this case by listening for the sessionDisconnected event with a reason of "networkDisconnected":

session.on({
  sessionDisconnected: function(event) {
    if (event.reason === 'networkDisconnected') {
      showMessage('You lost your internet connection.'
        + 'Please check your connection and try connecting again.');
    }
  }
});

Putting it all together

The following code includes a connect() method, which connects to a session. Once connected, the code tracks when clients join and leave the session. It also has a method for disconnecting from the session:

var session;
var connectionCount = 0;

function connect() {
  // Replace apiKey and sessionId with your own values:
  session = OT.initSession(apiKey, sessionId);
  session.on({
    connectionCreated: function (event) {
      connectionCount++;
      console.log(connectionCount + ' connections.');
    },
    connectionDestroyed: function (event) {
      connectionCount--;
      console.log(connectionCount + ' connections.');
    },
    sessionDisconnected: function sessionDisconnectHandler(event) {
      // The event is defined by the SessionDisconnectEvent class
      console.log('Disconnected from the session.');
      document.getElementById('disconnectBtn').style.display = 'none';
      if (event.reason == 'networkDisconnected') {
        alert('Your network connection terminated.')
      }
    }
  });
  // Replace token with your own value:
  session.connect(token, function(error) {
    if (error) {
      console.log('Unable to connect: ', error.message);
    } else {
      document.getElementById('disconnectBtn').style.display = 'block';
      console.log('Connected to the session.');
      connectionCount = 1;
    }
  });
}

function disconnect() {
  session.disconnect();
}

connect();