Migrating to version 2.2 of the OpenTok.js library

The OpenTok.js 2.2 library includes a set of new features that make it easier to develop OpenTok apps.

Loading the OpenTok.js 2.2 library

To use the new features available in version 2.2, set the src attribute of the script tag to load the new library:

<script src="//static.opentok.com/webrtc/v2.2/js/opentok.min.js"></script>

Migrating to the OpenTok.js 2.2 library

Important: The OpenTok.js 2.2 library includes changes that are not compatible with OpenTok.js 2.0. This section shows you how to adapt existing code to work with the OpenTok.js 2.2 library.

The OT object

The TB object has been renamed OT (for OpenTok). Note also that the URL for the OpenTok.js library now points to the opentok.min.js file:

<script src="//static.opentok.com/webrtc/v2.2/js/opentok.min.js"></script>

However, for backward compatibility, the JavaScript TB object will still work, and the TB.min.js URL will still work.

Connecting to a session

In the OpenTok.js 2.2 library, you pass your API key into the OT.initSession() method (as the first parameter):

var session = OT.initSession(apiKey, sessionId);
session.connect(token, function(error) {
  if (!error) {
    var publisher OT.initPublisher();
    session.publish(publisher);
  }
});

Note that the Session.connect() method and the OT.initPublisher() method do not take an API key as a parameter, since you pass the API key into the OT.initSession() method. (However, the old syntax is still supported.)

Breaking changes

We have tried to maintain backward compatibility with the the OpenTok.js 2.0 library. However, some of the v2.2 API changes require some code changes for apps ported from the OpenTok.js 2.0 library.

Changes to stream events for streams published by your client

The Session object does not dispatch streamCreated events for streams your own client publishes. To detect when a stream is created for your Publisher, add a completion handler for the Session.publish() method:

var publisher = session.publish(publisher, properties, function(error) {
  if (error) {
    console.log("Failed to publish.")
  } else {
    console.log("Stream publishing.")
  }
})

The Publisher object also dispatches a streamCreated event for the stream it publishes.

Additionally, in v2.2 the Publisher object (not the Session object) dispatches streamDestroyed events for the stream it publishes. If you want to retain the Publisher in the HTML DOM (for reuse), call the preventDefault() method in the event listener for the streamDestroyed event dispatched by the Publisher:

publisher = OT.initPublisher(apiKey)
  .on("streamDestroyed", function(event) {
    event.preventDefault(); // This lets you reuse the Publisher.
  }
);

Calling the preventDefault() method of the streamDestroyed and sessionDisconnected event objects dispatched by the Session object no longer prevents the Publisher object from being removed (as it did in v2.0).

For more details, see Changes to stream and connection events.

Detecting initial streams and connections in a session

In the OpenTok.js 2.2 library, the connections and streams property of the sessionConnected event are deprecated, and they are set to empty arrays. In v2.2, the Session object dispatches connectionCreated and streamCreated events for each client and stream in the session, both when you connect and after you connect.

To detect if another client was in the session when you connect, compare the connection.creationTime property of the connectionCreated event object with the connection.creationTime property of the Session object:

session.on("connectionCreated", function(event) {
  if (event.connection.creationTime <= session.connection.creationTime) {
    console.log("Detected a client that connected before you.")
  }
}

For more details, see Changes to stream and connection events.

Changes to the Session.signal() method

In the Session.signal() method, the data property of the signal parameter must be a string. (In OpenTok 2.0, the data property could be set to any JSON-serializable object.)

Also, the optional to property of the signal parameter takes a single Connection object (defining the connection to which the signal will be sent). The to property does not take an array of Connection objects, like it did in the OpenTok.js 2.0 library.

To send a signal to multiple individual clients connected to a session, call the signal() method repeatedly, passing in a single Connection object as the to parameter each time:

var connections;
// Set the connections object to an array of Connection objects corresponding to the clients you want to signal.

for (var i = 0; i < a.connections; i++) {
  session.signal(
    {
      type: "foo",
      to: connections[i],
      data: "hello"
    },
    function(error) {
      if (error) {
        console.log("signal error: " + error.reason);
      } else {
        console.log("signal sent");
      }
    }
  );
}

Other changes and new features

To learn about other changes and to start taking advantage of other new features, see New features in version 2.2.

New features

  • Intelligent quality control—You can now set a recommended video resolution and frame rate for a published stream. You can also reduce bandwidth usage of a Subscriber's video stream.
  • Completion handlers for methods—Some methods in the OpenTok.js 2.2 library now include an additional completionHandler parameter. This parameter is a function that is called when the method succeeds or fails.
  • New event registration methods—The OpenTok.js 2.2 library includes new methods — on(), once(), and off() — for adding and removing event listeners.
  • Changes to stream and connection events—The OpenTok.js 2.2 library includes improvements to events related to streams and clients entering and leaving OpenTok sessions.
  • Publisher and Subscriber DOM APIs—There are new APIs for Publisher and Subscriber insertion into and removal from the HTML DOM.
  • New Publisher.accessAllowed property—The accessAllowed property lets you see whether a client has allowed access to the camera and microphone.

Intelligent quality control

The OpenTok.js 2.2 library adds features for setting recommended video resolution and frame rate for a published stream.

To set a recommended video resolution for a published stream, set the resolution property of the properties parameter you pass into the OT.initPublisher() method:

var publisherProperties = {resolution: "1280x720"};
var publisher = OT.initPublisher(apiKey, targetElement, publisherProperties);

This resolution property is a string, defining the desired resolution of the video. The format of the string is "widthxheight", where the width and height are represented in pixels. Valid values are "1280x720", "640x480", and "320x240".

The requested resolution of a video stream is set as the videoDimensions.width and videoDimensions.height properties of the Stream object.

The default resolution for a stream (if you do not specify a resolution) is 640x480 pixels. If the client system cannot support the resolution you requested, the the stream will use the next largest setting supported.

To set a recommended frame rate for a published stream, set the frameRate property of the properties parameter you pass into the OT.initPublisher() method:

var publisherProperties = {frameRate: 7};
var publisher = OT.initPublisher(apiKey, targetElement, publisherProperties);

Set the value to the the desired frame rate, in frames per second, of the video. Valid values are 30, 15, 7, and 1.

If the publisher specifies a frame rate, the actual frame rate of the video stream is set as the frameRate property of the Stream object, though the actual frame rate will vary based on changing network and system conditions. If the developer does not specify a frame rate, this property is undefined.

For sessions that use the OpenTok Media Router (sessions with the media mode set to routed), lowering the frame rate or lowering the resolution reduces the maximum bandwidth the stream can use. However, in sessions that have the media mode set to relayed, lowering the frame rate or resolution may not reduce the stream's bandwidth.

You can also restrict the frame rate of a Subscriber's video stream. To restrict the frame rate a Subscriber, call the restrictFrameRate() method of the subscriber, passing in true:

mySubscriber.restrictFrameRate(true);

Pass in false and the frame rate of the video stream is not restricted:

mySubscriber.restrictFrameRate(false);

When the frame rate is restricted, the Subscriber video frame will update once or less per second.

This feature is only available in sessions media mode set to routed, not in sessions with the media mode set to relayed. In relayed sessions, calling this method has no effect.

Restricting the subscriber frame rate has the following benefits:

  • It reduces CPU usage.
  • It reduces the network bandwidth consumed by the app.
  • It lets you subscribe to more streams simultaneously.

Reducing a subscriber's frame rate has no effect on the frame rate of the video in other clients.

For more information about restricting subscriber bandwidth, see this blog post.

Finally, in sessions that use the OpenTok Media Router, a subscriber can drop to audio-only when the OpenTok Media Router determines that the client's network conditions do not support video. This feature was available in OpenTok.js 2.0. In the OpenTok 2.2 library, if the client's network connectivity improves enough to support video, the client dispatches a videoEnabled event, and the video resumes.

Completion handlers for methods

Some methods in the OpenTok.js 2.2 library now include a new completionHandler parameter. For this optional parameter, you can pass in a function that is called when the method succeeds or fails.

For example the connect() method of a Session object now includes a completionHandler parameter. This is the last parameter of the method. This function takes one parameter — error. On success, the completionHandler function is not passed any arguments. On error, the function is passed an error object parameter. The error object has two properties: code (an integer) and message (a string), which identify the cause of the failure. The following code adds a completionHandler when calling the connect() method:

// Set apiKey and token to your API key and a token for the session.
session.connect(apiKey, token, function(error) {
  if (error) {
    console.log(error.message);
  } else {
    console.log("Connected to session.");
  }
});

Note that upon connecting to the session, the Session object dispatches a sessionConnected event in addition to calling the completionHandler. However, the completionHandler in the OpenTok.js 2.2 library provides a standard way for checking the success or failure of a method call.

The following methods each include a completionHander parameter, as the last parameter of the method:

Check the message property for more details about the error.

In the event of an error, the code value of the error parameter is set to an Error object. For more information, see the documentation of the OpenTok Error class.

New event registration methods

The OpenTok.js 2.2 library includes new methods — on(), once(), and off() — for adding and removing event listeners. These methods are added to each class that can dispatch an event:

The addEventListener() and removeEventListener() methods are deprecated. They are replaced by the new methods. The new methods have the following advantages:

  • You can add or remove multiple event handlers in a single call to on() or off().

    For example, the following code adds event listeners for the accessAllowed, accessDenied, and streamDestroyed events for a Publisher object:

    publisher.on({
      accessAllowed: function (event) {
        // This is the handler for the accessAllowed event.
      },
      accessDenied:  function (event) {
        // This is the handler for accessDenied.
      }
      streamDestroyed: function (event) {
        // This is the handler for the streamDestroyed event.
      },
    });
    
  • The once() method lets you easily add an event listener that is called only once. (It is equivalent to calling on() and then calling off() in the event handler function.
  • You can use the context parameter to set the value of this in the handler method.

Changes to stream and connection events

The OpenTok.js 2.2 library adds a number of improvements to events related to streams and clients being added to and leaving a session.

One item per StreamEvent or ConnectionEvent

In OpenTok.js 2.2 library, the ConnectionEvent class, which defines the connectionCreated and connectionDestroyed events, has a connection property, representing the single Connection created or destroyed. The connections property (from v2.0) is deprecated.

Similarly, the StreamEvent class, which defines the streamCreated and streamDestroyed events, has a stream property, representing the single Stream created or destroyed. The streams property (from v2.0) is deprecated.

So, to detect other clients and their streams in a session (when you first connect or afterwards), simply register event listeners for the connectionCreated and streamCreated events dispatched by the session object:

var connectionCount = 0;
session.on(
  {
    connectionCreated: function(event) {
      connectionCount++;
      console.log("New client: " event.connection.connectionId);
      console.log("Clients in the session: " connectionCount);
    },
    connectionDestroyed: function(event) {
      connectionCount--;
      console.log("Client left the session: " event.connection.connectionId);
      console.log("Clients in the session: " connectionCount);
    },
    streamCreated: function(event) {
      console.log("Stream created: " event.stream.streamId);
      // This is another client's stream, so you may want to subscribe to it.
    },
    streamDestroyed: function(event) {
      console.log("Stream destroyed: " event.stream.streamId);
      // This is another client's stream leaving the session.
    }
  }
).connect(apiKey, token, function(error) {
  if (error) {
    console.log("Failed to connect: " error.message);
  } else {
    connectionCount++;
  }
});

Deprecating streams and connections from the sessionConnected event

In OpenTok.js 2.2 library, the connections and streams property of the sessionConnected event are deprecated, and they are set to empty arrays. In v2.2, the Session object dispatches connectionCreated and streamCreated events for each client and stream in the session, both when you connect and after you connect.

To detect other clients that exist in a session when you connect, compare the connection.creationTime property of the connectionCreated event and compare it with the connection.creationTime property of the Session object:

session.on("connectionCreated", function(event) {
  if (event.connection.creationTime <= session.connection.creationTime) {
    console.log("Detected a client that connected before you.")
  }
}

You can use the completion handler for the Session.connect() method instead of the sessionConnected event (as shown in the sample code).

Changes to events for streams you publish

In OpenTok.js 2.2 library, a Publisher object (not the Session object) dispatches streamCreated and streamDestroyed events for streams it publishes.

publisher = OT.initPublisher(apiKey)
  .on(
    {
      streamCreated: function(event) {
        // The Publisher started streaming.
      },
      streamDestroyed: function(event) {
        // The Publisher stopped streaming.
      }
    }
);

The Session object does not dispatch streamCreated events for streams your own client publishes. So, there is no need to check to see if this event corresponds to one of your own published streams. For example, if you want to subscribe to all third-party streams in the session, you can simply use the following code:

session.on("streamCreated", function(event) {
    session.subscribe(event.stream);
  },
}

Preserving a Publisher object when its stream is destroyed

If you want to retain the Publisher in the HTML DOM (for reuse), call the preventDefault() method in the event listener for the streamDestroyed event dispatched by the Publisher:

publisher = OT.initPublisher(apiKey)
  .on("streamDestroyed", function(event){
    event.preventDefault(); // This lets you reuse the Publisher.
  }
);

Calling the preventDefault() method of the sessionDisconnected event no longer causes a Publisher to be preserved.

Publisher and Subscriber DOM APIs

The OpenTok.js 2.2 library includes new APIs for Publisher and Subscriber insertion into and removal from the HTML DOM.

The insertMode property of the properties parameter of the OT.initPublisher() specifies how the Publisher object will be inserted in the HTML DOM, in relation to the targetElement parameter. You can set this parameter to one of the following values:

  • "replace" — The Publisher object replaces contents of the targetElement. This is the default.
  • "after" — The Publisher object is a new element inserted after the targetElement in the HTML DOM. (Both the Publisher and targetElement have the same parent element.)
  • "before" — The Publisher object is a new element inserted before the targetElement in the HTML DOM. (Both the Publisher and targetElement have the same parent element.)
  • "append" — The Publisher object is a new element added as a child of the targetElement. If there are other child elements, the Publisher is appended as the last child element of the targetElement.

For example, the following code adds a new Publisher object as a child of a publisherContainer DOM element:

var publisherProperties = {insertMode: "append"};
var publisher = OT.initPublisher('publisher', publisherContainer, function(error) {
  if (error) {
    console.log(error);
  } else {
    console.log("Publisher initialized.");
  }
});

Each Publisher and Subscriber object has an element property, which is set to the HTML DOM element containing the publisher or subscriber.

Each Publisher and Subscriber object dispatches a destroyed event when the object has been removed from the HTML DOM. In response to this event, you may choose to adjust (or remove) DOM elements related to the publisher or subscriber that was removed.

New Publisher.accessAllowed property

The new accessAllowed property indicates whether a client has granted access to the camera and microphone. In addition, the Publisher still dispatches accessAllowed and accessDenied events, as it did in version 2.0.

IRC Live Chat

Have a quick question? Chat with TokBox Support on IRC. Join chat