The latest version of the OpenTok.js library includes a set of new features that make it easier to develop OpenTok apps. This document describes changes that were added in version 2.2 (which are also in the latest version).
If you are migrating code from version 1.0 to this version, see this page.
To use the new features available in the latest version, set the src
attribute of the script
tag to load the new library:
<script src="https://static.opentok.com/v2/js/opentok.min.js"></script>
Important: The latest version of the OpenTok.js 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 latest version of the OpenTok.js library.
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="https://static.opentok.com/v2/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.
You now 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.)
We have tried to maintain backward compatibility with the the OpenTok.js 2.0 library. However, some of the API changes in the latest version of OpenTok.js require some code changes for apps ported from the OpenTok.js 2.0 library.
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).
In OpenTok.js 2.2+, the connections
and streams
property of the
sessionConnected
event are deprecated, and they are set to empty arrays. 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.
In the Session.signal()
method, the data
property of the
signal
parameter must be a string. (In OpenTok.js 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");
}
}
);
}
To learn about other changes and to start taking advantage of other new features, see New features in version 2.2.
This page describes features that were added in version 2.2. See the latest release notes for features that have been added since then.
completionHandler
parameter. This parameter is
a function that is called when the method succeeds or fails.on()
, once()
, and off()
— for adding and removing
event listeners.accessAllowed
property lets you see whether a client has allowed access to the camera and
microphone.The latest version of the OpenTok.js 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:
Reducing a subscriber's frame rate has no effect on the frame rate of the video in other clients.
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 latest version of the OpenTok.js library, if the client's network connectivity
improves enough to support video, the client dispatches a videoEnabled
event, and the
video resumes.
Some methods in the OpenTok.js 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 new OpenTok 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:
OT.initPublisher()
Session.connect()
Session.forceDisconnect()
Session.forceUnpublish()
Session.publish()
Session.signal()
Session.subscribe()
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.
The OpenTok.js library now 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:
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.
},
});
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.
context
parameter to set the value of this
in the handler method.
The OpenTok.js library now inclues a number of improvements to events related to streams and clients being added to and leaving a session.
The ConnectionEvent
class, which defines the connectionCreated
and
connectionDestroyed
events, now 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 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);
}
});
In the new OpenTok.js 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).
In the new OpenTok.js 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);
},
}
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.
The OpenTok.js library now 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.
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.