Suggestions

close search

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

Visit the Vonage API Developer Portal

Session

Properties Methods Events 

The Session object returned by the OT.initSession() method provides access to much of the Vonage Video API functionality.

Properties

Name Type Description
capabilities Capabilities A Capabilities object that includes information about the capabilities of the client. All properties of the capabilities object are undefined until you have connected to a session and the completion handler for the Session.connect() method has been called without error.
connection Connection The Connection object for this session. The connection property is only available once the completion handler for the Session.connect() method has been called successfully. See the Session.connect() method and the Connection class.
sessionId String The session ID for this session. You pass this value into the OT.initSession() method when you create the Session object. (Note: a Session object is not connected to the Vonage Video API server until you call the connect() method of the object and its completion handler is called without error. See the OT.initSession() and the Session.connect() methods.) For more information on sessions and session IDs, see Session creation.

Methods

Name Description
addEventListener(type, listener, context) Deprecated.
connect(token, completionHandler) Connects to a Vonage Video API session.
disableForceMute() → {Promise} Disables the active mute state of the session.
disconnect() Disconnects from the Vonage Video API session.
forceDisconnect(connection, completionHandler) Forces a remote connection to leave the session.
forceMuteAll(excludedStreams) → {Promise} Forces all publishers in the session (except for those publishing excluded streams) to mute audio.
forceMuteStream(stream) → {Promise} Forces a the publisher of a specified stream to mute its audio.
forceUnpublish(stream, completionHandler) Forces the publisher of the specified stream to stop publishing the stream.
getPublisherForStream(stream) → {Publisher} Returns the local Publisher object for a given stream.
getSubscribersForStream(stream) → {Array} Returns an array of local Subscriber objects for a given stream.
off(type, handler, context) → {Object} Removes an event handler or handlers.
on(type, handler, context) → {EventDispatcher} Adds an event handler function for one or more events.
once(type, handler, context) → {Object} Adds an event handler function for one or more events.
publish(publisher, completionHandler) The publish() method starts publishing an audio-video stream to the session.
removeEventListener(type, listener, context) Deprecated.
setEncryptionSecret(secret) → {Promise} Sets the encryption secret for a session with end-to-end encryption enabled.
setIceConfig(newIceConfig) Sets the ICE configuration for all connections in a session.
signal(signal, completionHandler) Sends a signal to each client or a specified client in the session.
subscribe(stream, targetElement, properties, completionHandler) → {Subscriber} Subscribes to a stream that is available to the session.
unpublish(publisher) Ceases publishing the specified publisher's audio-video stream to the session.
unsubscribe(subscriber) Stops subscribing to a stream in the session.

addEventListener(type, listener, context)

Parameters:
Name Type Description
type String The string identifying the type of event.
listener function The function to be invoked when the object dispatches the event.
context Object (Optional) Defines the value of this in the event handler function.

Deprecated — use on() or once() instead.

This method registers a method as an event listener for a specific event.

If a handler is not registered for an event, the event is ignored locally. If the event listener function does not exist, the event is ignored locally.

Throws an exception if the listener name is invalid.

See:

connect(token, completionHandler)

Connects to a Vonage Video API session.

Upon a successful connection, the completion handler (the second parameter of the method) is invoked without an error object passed in. (If there is an error connecting, the completion handler is invoked with an error object.) Make sure that you have successfully connected to the session before calling other methods of the Session object.

The Session object dispatches a connectionCreated event when any client (including your own) connects to the session.

Example

The following code initializes a session and sets up an event listener for when the session connects:

 var apiKey = ""; // Replace with your API key. See https://tokbox.com/account
 var sessionID = ""; // Replace with your own session ID.
                     // See https://tokbox.com/developer/guides/create-session/.
 var token = ""; // Replace with a generated token.
                 // See https://tokbox.com/developer/guides/create-token/.

 var session = OT.initSession(apiKey, sessionID);
 session.connect(token, function(error) {
   if (error) {
     console.log(error.message);
   } else {
     // You have connected to the session. You could publish a stream now.
   }
 });

Events dispatched:

exception (ExceptionEvent) — Dispatched by the OT class locally in the event of an error.

connectionCreated (ConnectionEvent) — Dispatched by the Session object on all clients connected to the session.

sessionConnected (SessionConnectEvent) — Dispatched locally by the Session object when the connection is established. However, you can pass a completion handler function in as the second parameter of the connect() and use this function instead of a listener for the sessionConnected event.

Parameters:
Name Type Description
token String The session token. You generate a session token using our server-side libraries or at your Vonage Video API account page. For more information, see Connection token creation.
completionHandler function (Optional) A function to be called when the call to the connect() method succeeds or fails. This function takes one parameter — error (see the Error object). On success, the completionHandler function is not passed any arguments. On error, the function is passed an error object parameter (see the Error object). 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:
session.connect(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. The SessionConnectEvent object, which defines the sessionConnected event, includes connections and streams properties, which list the connections and streams in the session when you connect.

See:

disableForceMute() → {Promise}

Disables the active mute state of the session. After you call this method, new streams published to the session will no longer have audio muted.

After you call to the Session.forceMuteAll() method (or a moderator in another client makes a call to mute all streams), any streams published after the moderation call are published with audio muted. Call the disableForceMute() method to remove the mute state of a session (so that new published streams are not automatically muted).

Calling this method causes the Session object in each connected clients to dispatch a muteForced event, with the active flag set to false.

Check the capabilities.canForceMute property of the Session object to see if you can call this function successfully. This is reserved for clients that have connected with a token that has been assigned the moderator role (see the Token Creation documentation).

See:
Returns:
A promise that resolves with no value when the operation completes successfully. The promise is rejected if there is an error. The name property of the Error object is set to one of the following values, depending the type of error:

  • 'OT_NOT_CONNECTED' — The client is not connect to the session.
  • 'OT_PERMISSION_DENIED' — The user's role does not include permissions required to force other users to mute. You define a user's role when you create the user token (see the Token creation overview). You pass the token string as a parameter of the connect() method of the Session object.
  • 'OT_UNEXPECTED_SERVER_RESPONSE' — In case of an internal server error.

disconnect()

Disconnects from the Vonage Video API session.

Calling the disconnect() method ends your connection with the session. In the course of terminating your connection, it also ceases publishing any stream(s) you were publishing.

Session objects on remote clients dispatch streamDestroyed events for any stream you were publishing. The Session object dispatches a sessionDisconnected event locally. The Session objects on remote clients dispatch connectionDestroyed events, letting other connections know you have left the session. The SessionDisconnectEvent and StreamEvent objects that define the sessionDisconnect and connectionDestroyed events each have a reason property. The reason property lets the developer determine whether the connection is being terminated voluntarily and whether any streams are being destroyed as a byproduct of the underlying connection's voluntary destruction.

If the session is not currently connected, calling this method causes a warning to be logged. See OT.setLogLevel().

Note: If you intend to reuse a Publisher object to publish to different sessions (or the same session) sequentially, add an event listener for the streamDestroyed event dispatched by the Publisher object (when it stops publishing). In the event listener, call the preventDefault() method of the event object to prevent the Publisher's video from being removed from the page.

Events dispatched:

sessionDisconnected (SessionDisconnectEvent) — Dispatched locally when the connection is disconnected.

connectionDestroyed (ConnectionEvent) — Dispatched on other clients, along with the streamDestroyed event (as warranted).

streamDestroyed (StreamEvent) — Dispatched on other clients if streams are lost as a result of the session disconnecting.

forceDisconnect(connection, completionHandler)

Forces a remote connection to leave the session.

The forceDisconnect() method is normally used as a moderation tool to remove users from an ongoing session.

When a connection is terminated using the forceDisconnect(), sessionDisconnected, connectionDestroyed and streamDestroyed events are dispatched in the same way as they would be if the connection had terminated itself using the disconnect() method. However, the reason property of a ConnectionEvent or StreamEvent object specifies "forceDisconnected" as the reason for the destruction of the connection and stream(s).

While you can use the forceDisconnect() method to terminate your own connection, calling the disconnect() method is simpler.

The OT object dispatches an exception event if the user's role does not include permissions required to force other users to disconnect. You define a user's role when you create the user token (see the Token creation overview). See ExceptionEvent and OT.on().

The application throws an error if the session is not connected.

Events dispatched:

connectionDestroyed (ConnectionEvent) — On clients other than which had the connection terminated.

exception (ExceptionEvent) — The user's role does not allow forcing other user's to disconnect (event.code = 1530), or the specified stream is not publishing to the session (event.code = 1535).

sessionDisconnected (SessionDisconnectEvent) — On the client which has the connection terminated.

streamDestroyed (StreamEvent) — If streams are stopped as a result of the connection ending.

Parameters:
Name Type Description
connection Connection The connection to be disconnected from the session. This value can either be a Connection object or a connection ID (which can be obtained from the connectionId property of the Connection object).
completionHandler function (Optional) A function to be called when the call to the forceDiscononnect() method succeeds or fails. 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, defined by the Error class, has two properties: code (an integer) and message (a string), which identify the cause of the failure. Calling forceDisconnect() fails if the role assigned to your token is not "moderator"; in this case the error.name property is set to "OT_PERMISSION_DENIED". The following code adds a completionHandler when calling the forceDisconnect() method:
session.forceDisconnect(connection, function (error) {
  if (error) {
    console.log(error);
  } else {
    console.log("Connection forced to disconnect: " + connection.id);
  }
});

forceMuteAll(excludedStreams) → {Promise}

Forces all publishers in the session (except for those publishing excluded streams) to mute audio.

A stream published by the moderator calling the forceMuteAll() method is muted along with other streams in the session, unless you add the moderator's stream (or streams) to the excluded streams array.

If you leave out the excludedStreams parameter, all streams in the session (including those of the moderator) will stop publishing audio:

session.forceMuteAll();

Also, any streams that are published after the call to the forceMuteAll() method are published with audio muted. You can remove the mute state of a session by calling the disableForceMute() method of the Session object.

session.disableForceMute();

After you call the Session.disableForceMute() method, new streams published to the session will no longer have audio muted.

Calling this method causes the Publisher objects in the clients publishing the streams to dispatch muteForced events. Also, the Session object in each client connected to the session dispatches the muteForced event (with the active property of the event object set to true).

Check the capabilities.canForceMute property of the Session object to see if you can call this function successfully. This is reserved for clients that have connected with a token that has been assigned the moderator role (see the Token Creation documentation).

Parameters:
Name Type Description
excludedStreams Array An array of Stream objects to be excluded from being muted. Note that if you want to prevent the local client's published stream(s) from being muted, include the Stream object(s) for those stream(s) in this array.
See:
Returns:
A promise that resolves with no value when the operation completes successfully. The promise is rejected if there is an error. The name property of the Error object is set to one of the following values, depending the type of error:

  • 'OT_NOT_CONNECTED' — The client is not connect to the session.
  • 'INVALID_PARAMETER' — if one or more of the passed parameters are invalid.
  • 'OT_PERMISSION_DENIED' — The user's role does not include permissions required to force other users to mute. You define a user's role when you create the user token (see the Token creation overview). You pass the token string as a parameter of the connect() method of the Session object.
  • 'OT_UNEXPECTED_SERVER_RESPONSE' — in case of an internal server error.

forceMuteStream(stream) → {Promise}

Forces a the publisher of a specified stream to mute its audio.

Calling this method causes the Publisher object in the client publishing the stream to dispatch a muteForced event.

Check the capabilities.canForceMute property of the Session object to see if you can call this function successfully. This is reserved for clients that have connected with a token that has been assigned the moderator role (see the Token Creation documentation).

Parameters:
Name Type Description
stream Stream The stream to be muted.
See:
Returns:
A promise that resolves with no value when the operation completes successfully. The promise is rejected if there is an error. The name property of the Error object is set to one of the following values, depending the type of error:

  • 'OT_NOT_CONNECTED' — The client is not connect to the session.
  • 'OT_INVALID_PARAMETER' — if one or more of the passed parameters are invalid.
  • 'OT_PERMISSION_DENIED' — The user's role does not include permissions required to force other users to mute. You define a user's role when you create the user token (see the Token creation overview). You pass the token string as a parameter of the connect() method of the Session object.
  • 'OT_NOT_FOUND' — The stream wasn't found in this session.
  • 'OT_UNEXPECTED_SERVER_RESPONSE' — In case of an internal server error.

forceUnpublish(stream, completionHandler)

Forces the publisher of the specified stream to stop publishing the stream.

Calling this method causes the Session object to dispatch a streamDestroyed event on all clients that are subscribed to the stream (including the client that is publishing the stream). The reason property of the StreamEvent object is set to "forceUnpublished".

The OT object dispatches an exception event if the user's role does not include permissions required to force other users to unpublish. You define a user's role when you create the user token (see the Token creation overview). You pass the token string as a parameter of the connect() method of the Session object. See ExceptionEvent and OT.on().

Events dispatched:

exception (ExceptionEvent) — The user's role does not allow forcing other users to unpublish.

streamDestroyed (StreamEvent) — The stream has been unpublished. The Session object dispatches this on all clients subscribed to the stream, as well as on the publisher's client.

Parameters:
Name Type Description
stream Stream The stream to be unpublished.
completionHandler function (Optional) A function to be called when the call to the forceUnpublish() method succeeds or fails. 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, defined by the Error class, has two properties: code (an integer) and message (a string), which identify the cause of the failure. Calling forceUnpublish() fails if the role assigned to your token is not "moderator"; in this case the error.name property is set to "OT_PERMISSION_DENIED". The following code adds a completion handler when calling the forceUnpublish() method:
session.forceUnpublish(stream, function (error) {
  if (error) {
      console.log(error);
    } else {
      console.log("Connection forced to disconnect: " + connection.id);
    }
  });

getPublisherForStream(stream) → {Publisher}

Returns the local Publisher object for a given stream.
Parameters:
Name Type Description
stream Stream The stream for which you want to find the Publisher.
See:
Returns:
A Publisher object for the specified stream. Returns null if there is no local Publisher object for the specified stream.

getSubscribersForStream(stream) → {Array}

Returns an array of local Subscriber objects for a given stream.
Parameters:
Name Type Description
stream Stream The stream for which you want to find subscribers.
See:
Returns:
An array of Subscriber objects for the specified stream.

off(type, handler, context) → {Object}

Removes an event handler or handlers.

If you pass in one event name and a handler method, the handler is removed for that event:

obj.off("eventName", eventHandler);

If you pass in multiple event names and a handler method, the handler is removed for those events:

obj.off("eventName1 eventName2", eventHandler);

If you pass in an event name (or names) and no handler method, all handlers are removed for those events:

obj.off("event1Name event2Name");

If you pass in no arguments, all event handlers are removed for all events dispatched by the object:

obj.off();

The method also supports an alternate syntax, in which the first parameter is an object that is a hash map of event names and handler functions and the second parameter (optional) is the context for this in each handler:

obj.off(
   {
      eventName1: event1Handler,
      eventName2: event2Handler
   });
Parameters:
Name Type Description
type String (Optional) The string identifying the type of event. You can use a space to specify multiple events, as in "accessAllowed accessDenied accessDialogClosed". If you pass in no type value (or other arguments), all event handlers are removed for the object.
handler function (Optional) The event handler function to remove. The handler must be the same function object as was passed into on(). Be careful with helpers like bind() that return a new function when called. If you pass in no handler, all event handlers are removed for the specified event type.
context Object (Optional) If you specify a context, the event handler is removed for all specified events and handlers that use the specified context. (The context must match the context passed into on().)
See:
Returns:
The object that dispatched the event.

on(type, handler, context) → {EventDispatcher}

Adds an event handler function for one or more events.

The following code adds an event handler for one event:

obj.on("eventName", function (event) {
    // This is the event handler.
});

If you pass in multiple event names and a handler method, the handler is registered for each of those events:

obj.on("eventName1 eventName2",
       function (event) {
           // This is the event handler.
       });

You can also pass in a third context parameter (which is optional) to define the value of this in the handler method:

obj.on("eventName",
       function (event) {
           // This is the event handler.
       },
       obj);

The method also supports an alternate syntax, in which the first parameter is an object that is a hash map of event names and handler functions and the second parameter (optional) is the context for this in each handler:

obj.on(
   {
      eventName1: function (event) {
              // This is the handler for eventName1.
          },
      eventName2:  function (event) {
              // This is the handler for eventName2.
          }
   },
   obj);

If you do not add a handler for an event, the event is ignored locally.

Parameters:
Name Type Description
type String The string identifying the type of event. You can specify multiple event names in this string, separating them with a space. The event handler will process each of the events.
handler function The handler function to process the event. This function takes the event object as a parameter.
context Object (Optional) Defines the value of this in the event handler function.
See:
Returns:
The EventDispatcher object.

once(type, handler, context) → {Object}

Adds an event handler function for one or more events. Once the handler is called, the specified handler method is removed as a handler for this event. (When you use the on() method to add an event handler, the handler is not removed when it is called.) The once() method is the equivilent of calling the on() method and calling off() the first time the handler is invoked.

The following code adds a one-time event handler for one event:

obj.once("eventName", function (event) {
   // This is the event handler.
});

If you pass in multiple event names and a handler method, the handler is registered for each of those events:

obj.once("eventName1 eventName2"
         function (event) {
             // This is the event handler.
         });

You can also pass in a third context parameter (which is optional) to define the value of this in the handler method:

obj.once("eventName",
         function (event) {
             // This is the event handler.
         },
         obj);

The method also supports an alternate syntax, in which the first parameter is an object that is a hash map of event names and handler functions and the second parameter (optional) is the context for this in each handler:

obj.once(
   {
      eventName1: function (event) {
                 // This is the event handler for eventName1.
          },
      eventName2:  function (event) {
                 // This is the event handler for eventName1.
          }
   },
   obj);
Parameters:
Name Type Description
type String The string identifying the type of event. You can specify multiple event names in this string, separating them with a space. The event handler will process the first occurence of the events. After the first event, the handler is removed (for all specified events).
handler function The handler function to process the event. This function takes the event object as a parameter.
context Object (Optional) Defines the value of this in the event handler function.
See:
Returns:
The object that dispatched the event.

publish(publisher, completionHandler)

The publish() method starts publishing an audio-video stream to the session. The audio-video stream is captured from a local microphone and webcam. Upon successful publishing, the Session objects on all connected clients dispatch the streamCreated event.

You pass a Publisher object as the one parameter of the method. You can initialize a Publisher object by calling the OT.initPublisher() method. Before calling Session.publish().

This method takes an alternate form: publish(targetElement: String | HTMLElement, properties: Object, completionHandler: Function): Publisher — In this form, you do not pass a Publisher object into the function. Instead, you pass in a targetElement (the target HTML element or the ID of the target HTML element for the Publisher), an optional properties object that defines options for the Publisher (see OT.initPublisher()), and an optional completion handler function. The method returns a new Publisher object, which starts sending an audio-video stream to the session. The remainder of this documentation describes the form that takes a single Publisher object as a parameter.

A local display of the published stream is created on the web page by replacing the specified element in the DOM with a streaming video display. The video stream is automatically mirrored horizontally so that users see themselves and movement in their stream in a natural way. If the width and height of the display do not match the 4:3 aspect ratio of the video signal, the video stream is cropped to fit the display.

If calling this method creates a new Publisher object and the Vonage Video API library does not have access to the camera or microphone, the web page alerts the user to grant access to the camera and microphone.

The OT object dispatches an exception event if the user's role does not include permissions required to publish. For example, if the user's role is set to subscriber, then they cannot publish. You define a user's role when you create the user token (see Token creation overview). You pass the token string as a parameter of the connect() method of the Session object. See ExceptionEvent and OT.on().

The application throws an error if the session is not connected.

Events dispatched:

exception (ExceptionEvent) — Dispatched by the OT object. This can occur when user's role does not allow publishing (the code property of event object is set to 1500); it can also occur if the connection fails to connect (the code property of event object is set to 1013). WebRTC is a peer-to-peer protocol, and it is possible that connections will fail to connect. The most common cause for failure is a firewall that the protocol cannot traverse.

streamCreated (StreamEvent) — The stream has been published. The Session object dispatches this on all clients subscribed to the stream, as well as on the publisher's client.

Example

The following example publishes a video once the session connects:

var apiKey = ""; // Replace with your API key. See https://tokbox.com/account
var sessionId = ""; // Replace with your own session ID.
                    // /developer/guides/create-session/.
var token = ""; // Replace with a generated token that has been assigned the publish role.
                // See https://tokbox.com/developer/guides/create-token/.
var session = OT.initSession(apiKey, sessionID);
session.connect(token, function(error) {
  if (error) {
    console.log(error.message);
  } else {
    var publisherOptions = {width: 400, height:300, name:"Bob's stream"};
    // This assumes that there is a DOM element with the ID 'publisher':
    publisher = OT.initPublisher('publisher', publisherOptions);
    session.publish(publisher);
  }
});
Parameters:
Name Type Description
publisher Publisher A Publisher object, which you initialize by calling the OT.initPublisher() method.
completionHandler function (Optional) A function to be called when the call to the publish() method succeeds or fails. 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 (see the Error object). The error object has two properties: code (an integer) and message (a string), which identify the cause of the failure. Calling publish() fails if the role assigned to your token is not "publisher" or "moderator"; in this case the error.name property is set to "OT_PERMISSION_DENIED". Calling publish() also fails if the client fails to connect; in this case the error.name property is set to "OT_NOT_CONNECTED". The following code adds a completion handler when calling the publish() method:
session.publish(publisher, null, function (error) {
  if (error) {
    console.log(error.message);
  } else {
    console.log("Publishing a stream.");
  }
});
Returns:
The Publisher object for this stream.

removeEventListener(type, listener, context)

Parameters:
Name Type Description
type String The string identifying the type of event.
listener function The event listener function to remove.
context Object (Optional) If you specify a context, the event handler is removed for all specified events and event listeners that use the specified context. (The context must match the context passed into addEventListener().)

Deprecated — use off() instead.

Removes an event listener for a specific event.

Throws an exception if the listener name is invalid.

See:

setEncryptionSecret(secret) → {Promise}

Sets the encryption secret for a session with end-to-end encryption enabled. If this method is called in a session without encryption enabled the function will resolve and no error will be thrown. Users may change their set encryption key at any time. See the end-to-end encryption developer guide.
Parameters:
Name Type Description
secret string The encryption secret.
See:
Returns:
A promise that resolves with no value when the operation completes successfully. The promise is rejected if there is an error. The name property of the Error object is set to one of the following values, depending the type of error:

  • 'OT_INVALID_ENCRYPTION_SECRET'; The secret is invalid.
    • A secret mismatch may occur when no error is dispatched. See subscrriber events for more information.

setIceConfig(newIceConfig)

Sets the ICE configuration for all connections in a session. This replaces any previously set ICE configurations.

This feature is available for projects that use the configurable TURN server add-on.

Parameters:
Name Type Description
newIceConfig IceConfig This object defines the ICE configuration. It has the following propoerties;

  • includeServers (String) — Set this to 'custom' and client will use only the custom TURN servers you provide in the customServers property of the newIceConfig parameter. Set this to 'all' and the client will use both the custom TURN servers you provide along with Vonage Video API TURN servers.
  • transportPolicy (String) — Set this to 'all' (the default) and the client will use all ICE transport types (such as host, srflx, and TURN) to establish media connectivity. Set this to 'relay' to force connectivity through TURN always and ignore all other ICE candidates.
  • customServers (Array) — Set this to an array of objects defining your custom TURN servers. Each object corresponds to one custom TURN server, and it includes the following properties:

    • urls (String or Array of Strings) — A string or an array of strings, where each string is a URL supported by the TURN server (and this may be only one URL).
    • username (String, optional) — The username for the TURN server defined in this object.
    • credential (String, optional) — The credential string for the TURN server defined in this object.

See:

signal(signal, completionHandler)

Sends a signal to each client or a specified client in the session. Specify a to property of the signal parameter to limit the signal to be sent to a specific client; otherwise the signal is sent to each client connected to the session.

The following example sends a signal of type "foo" with a specified data payload ("hello") to all clients connected to the session:

session.signal({
    type: "foo",
    data: "hello"
  },
  function(error) {
    if (error) {
      console.log("signal error: " + error.message);
    } else {
      console.log("signal sent");
    }
  }
);

Calling this method without specifying a recipient client (by setting the to property of the signal parameter) results in multiple signals sent (one to each client in the session). For information on charges for signaling, see the Vonage Video API pricing page.

The following example sends a signal of type "foo" with a data payload ("hello") to a specific client connected to the session:

session.signal({
    type: "foo",
    to: recipientConnection; // a Connection object
    data: "hello"
  },
  function(error) {
    if (error) {
      console.log("signal error: " + error.message);
    } else {
      console.log("signal sent");
    }
  }
);

Add an event handler for the signal event to listen for all signals sent in the session. Add an event handler for the signal:type event to listen for signals of a specified type only (replace type, in signal:type, with the type of signal to listen for). The Session object dispatches these events. (See events.)

Parameters:
Name Type Description
signal Object An object that contains the following properties defining the signal:
  • data — (String) The data to send. The limit to the length of data string is 8kB. Do not set the data string to null or undefined.
  • retryAfterReconnect— (Boolean) Upon reconnecting to the session, whether to send any signals that were initiated while disconnected. If your client loses its connection to the Vonage Video API session, due to a drop in network connectivity, the client attempts to reconnect to the session, and the Session object dispatches a reconnecting event. By default, signals initiated while disconnected are sent when (and if) the client reconnects to the Vonage Video API session. You can prevent this by setting the retryAfterReconnect property to false. (The default value is true.)
  • to — (Connection) A Connection object corresponding to the client that the message is to be sent to. If you do not specify this property, the signal is sent to all clients connected to the session.
  • type — (String) The type of the signal. You can use the type to filter signals when setting an event handler for the signal:type event (where you replace type with the type string). The maximum length of the type string is 128 characters, and it must contain only letters (A-Z and a-z), numbers (0-9), '-', '_', and '~'.

Each property is optional. If you set none of the properties, you will send a signal with no data or type to each client connected to the session.

completionHandler function (Optional) A function that is called when sending the signal succeeds or fails. 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, defined by the Error class. The error object has the following properties:
  • code — (Number) An error code, which can be one of the following:
    400 One of the signal properties is invalid.
    404 The client specified by the to property is not connected to the session.
    413 The type string exceeds the maximum length (128 bytes), or the data string exceeds the maximum size (8 kB).
    500 You are not connected to the Vonage Video API session.
  • message — (String) A description of the error.

Note that the completionHandler success result (error == null) indicates that the options passed into the Session.signal() method are valid and the signal was sent. It does not indicate that the signal was successfully received by any of the intended recipients.

See:

subscribe(stream, targetElement, properties, completionHandler) → {Subscriber}

Subscribes to a stream that is available to the session. You can get an array of available streams from the streams property of the sessionConnected and streamCreated events (see SessionConnectEvent and StreamEvent).

The subscribed stream is displayed on the local web page by replacing the specified element in the DOM with a streaming video display. If the width and height of the display do not match the 4:3 aspect ratio of the video signal, the video stream is cropped to fit the display. If the stream lacks a video component, a blank screen with an audio indicator is displayed in place of the video stream.

The application throws an error if the session is not connected or if the targetElement does not exist in the HTML DOM.

Example
The following code subscribes to other clients' streams:
var apiKey = ""; // Replace with your API key. See https://tokbox.com/account
var sessionID = ""; // Replace with your own session ID.
                    // See https://tokbox.com/developer/guides/create-session/.
var token = ""; // Replace with a generated token.
                // See https://tokbox.com/developer/guides/create-token/.

var session = OT.initSession(apiKey, sessionID);
session.on("streamCreated", function(event) {
  subscriber = session.subscribe(event.stream, targetElement);
});
session.connect(token);
Parameters:
Name Type Description
stream Stream The Stream object representing the stream to which we are trying to subscribe.
targetElement Object (Optional) The DOM element or the id attribute of the existing DOM element used to determine the location of the Subscriber video in the HTML DOM. See the insertMode property of the properties parameter. If you do not specify a targetElement, the application appends a new DOM element to the HTML body.
properties Object This is an object that contains the following properties:
  • audioVolume (Number) — The desired audio volume, between 0 and 100, when the Subscriber is first opened (default: 50). After you subscribe to the stream, you can adjust the volume by calling the setAudioVolume() method of the Subscriber object. This volume setting affects local playback only; it does not affect the stream's volume on other clients.
  • fitMode (String) — Determines how the video is displayed if the its dimensions do not match those of the DOM element. You can set this property to one of the following values:

    • "cover" — The video is cropped if its dimensions do not match those of the DOM element. This is the default setting for videos that have a camera as the source (for Stream objects with the videoType property set to "camera").
    • "contain" — The video is letterboxed if its dimensions do not match those of the DOM element. This is the default setting for screen-sharing videos (for Stream objects with the videoType property set to "screen").
  • height (Number or String) — The desired initial height of the displayed video in the HTML page (default: 198 pixels). You can specify the number of pixels as either a number (such as 300) or a string ending in "px" (such as "300px"). Or you can specify a percentage of the size of the parent element, with a string ending in "%" (such as "100%"). Note: To resize the video, adjust the CSS of the subscriber's DOM element (the element property of the Subscriber object) or (if the height is specified as a percentage) its parent DOM element (see Resizing or repositioning a video).
  • insertDefaultUI (Boolean) — Whether to use the default Vonage Video API UI (true, the default) or not (false). The default UI element contains user interface controls, a video loading indicator, and automatic video cropping or letterboxing, in addition to the video. (If you leave insertDefaultUI set to true, you can control individual UI settings using the fitMode, showControls, and style options.)

    If you set this option to false, OpenTok.js does not insert a default UI element in the HTML DOM, and the element property of the Subscriber object is undefined. The Subscriber object dispatches a videoElementCreated event when the video element (or in Internet Explorer the object element containing the video) is created. The element property of the event object is a reference to the Subscriber's video (or object) element. Add it to the HTML DOM to display the video.

    Set this option to false if you want to move the Publisher's video element (or its object element in Internet Explorer) in the HTML DOM.

    If you set this to false, do not set the targetElement parameter. (This results in an error passed into to the OT.initPublisher() callback function.) To add the video to the HTML DOM, add an event listener for the videoElementCreated event, and then add the element property of the event object into the HTML DOM.

  • insertMode (String) — Specifies how the Subscriber object will be inserted in the HTML DOM. See the targetElement parameter. This string can have the following values:

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

  • preferredFrameRate (Number) — The preferred frame rate of the subscriber's video. Lowering the preferred frame rate lowers video quality on the subscribing client, but it also reduces network and CPU usage. You may want to use a lower frame rate for subscribers to a stream that is less important than other streams.

    This property only applies when subscribing to a stream that uses the scalable video feature. Scalable video is available:

    • Only in sessions that use the Vonage Video API Media Router (sessions with the media mode set to routed).
    • Only for streams published by clients that support scalable video: clients that use the Vonage Video API iOS SDK (on certain devices), the Vonage Video API Android SDK (on certain devices), or OpenTok.js in Chrome and Safari.

    In streams that do not use scalable video, setting this property has no effect.

    Note: The frame rate for scalable video streams automatically adjusts for each subscriber, based on network conditions and CPU usage, even if you do not call this method. Call this method if you want to set a maximum frame rate for this subscriber.

    Not every frame rate is available to a subscriber. When you set the preferred frame rate for the subscriber, OpenTok.js picks the best frame rate available that matches your setting. The frame rates available are based on the value of the Subscriber object's stream.frameRate property, which represents the maximum value available for the stream. The actual frame rates available depend, dynamically, on network and CPU resources available to the publisher and subscriber.

    You can dynamically change the preferred frame rate used by calling the setPreferredFrameRate() method of the Subscriber object.

  • preferredResolution (String | Object) — The preferred resolution of the subscriber's video. Set this to "auto" (a string, recommended) to have OpenTok.js set the resolution based on the subscriber's dimensions in the browser. Or set this to an object with two properties: width and height (both numbers), such as {width: 320, height: 240}. Lowering the preferred video resolution lowers video quality on the subscribing client, but it also reduces network and CPU usage. You may want to use a lower resolution based on the dimensions of subscriber's video on the web page (which is handled automatically with the "auto" setting). Or you may want to use a resolution for subscribers to a stream that is less important (and smaller) than other streams.

    Note: The "auto" resolution setting only applies when you use the default Subscriber Video element created by the SDK. It does not work if you create your own Video element in response to the mediaStreamAvailable event (see this topic).

    This property only applies when subscribing to a stream that uses the scalable video feature. Scalable video is available:

    • Only in sessions that use the Vonage Video API Media Router (sessions with the media mode set to routed).
    • Only for streams published by clients that support scalable video: clients that use the Vonage Video API iOS SDK (on certain devices), the Vonage Video API Android SDK (on certain devices), or OpenTok.js in Chrome and Safari.

    In streams that do not use scalable video, setting this property has no effect.

    Not every resolution is available to a subscriber. When you set the preferred resolution, OpenTok.js and the video encoder pick the best resolution available that matches your setting. The resolutions available depend on the resolution of the published stream. The Subscriber object's stream.resolution property represents the highest resolution available for the stream. Each of the resolutions available for a stream will use the same aspect ratio. The actual resolutions available depend, dynamically, on network and CPU resources available to the publisher and subscriber.

    You can dynamically change the preferred video resolution used by calling the setPreferredResolution() method of the Subscriber object.

  • showControls (Boolean) — Whether to display the built-in user interface controls for the Subscriber (default: true). These controls include the name display, the audio level indicator, the speaker control button, the video disabled indicator, and the video disabled warning icon. You can turn off all user interface controls by setting this property to false. You can control the display of individual user interface controls by leaving this property set to true (the default) and setting individual properties of the style property.
  • style (Object) — An object containing properties that define the initial appearance of user interface controls of the Subscriber. The style object includes the following properties:
    • audioBlockedDisplayMode (String) — Whether to display the default audio blocked icon in Subscribers (in browsers where audio autoplay is blocked). Possible values are: "auto" (the default, icon is displayed when the audio is disabled) and "off" (the icon is not displayed). Set this to "off" if you want to display your own UI element showing that the audio is blocked. In response to an HTML element dispatching a click event, you can call the OT.unblockAudio() method to start audio playback in this and all other blocked subscribers.
    • audioLevelDisplayMode (String) — How to display the audio level indicator. Possible values are: "auto" (the indicator is displayed when the video is disabled), "off" (the indicator is not displayed), and "on" (the indicator is always displayed).
    • backgroundImageURI (String) — A URI for an image to display as the background image when a video is not displayed. (A video may not be displayed if you call subscribeToVideo(false) on the Subscriber object). You can pass an http or https URI to a PNG, JPEG, or non-animated GIF file location. You can also use the data URI scheme (instead of http or https) and pass in base-64-encrypted PNG data, such as that obtained from the Subscriber.getImgData() method. (For example, you could set the property to a value returned by calling getImgData() on a previous Subscriber object.) If the URL or the image data is invalid, the property is ignored (the attempt to set the image fails silently).
    • buttonDisplayMode (String) — How to display the speaker controls Possible values are: "auto" (controls are displayed when the stream is first displayed and when the user mouses over the display), "off" (controls are not displayed), and "on" (controls are always displayed).
    • nameDisplayMode (String) — Whether to display the stream name. Possible values are: "auto" (the name is displayed when the stream is first displayed and when the user mouses over the display), "off" (the name is not displayed), and "on" (the name is always displayed).
    • videoDisabledDisplayMode (String) — Whether to display the video disabled indicator and video disabled warning icons for a Subscriber. These icons indicate that the video has been disabled (or is at risk of being disabled for the warning icon) due to poor stream quality. This style only applies to the Subscriber object. Possible values are: "auto" (the icons are automatically when the displayed video is disabled or at risk of being disabled due to poor stream quality), "off" (do not display the icons), and "on" (display the icons). The default setting is "auto"
  • subscribeToAudio (Boolean) — Whether to initially subscribe to audio (if available) for the stream (default: true).
  • subscribeToVideo (Boolean) — Whether to initially subscribe to video (if available) for the stream (default: true).
  • testNetwork (Boolean) — Whether, when subscribing to a stream published by the local client, you want to have the stream come from the Vonage Video API Media Router (true) or if you want the DOM to simply to display the local camera's video (false). Set this to true when you want to use the Subscriber.getStats() method to check statistics for a stream you publish. This setting only applies to streams published by the local client in a session that uses the Vonage Video API Media Router (sessions with the media mode set to routed), not in sessions with the media mode set to relayed. The default value is false.
  • width (Number or String) — The desired initial width of the displayed video in the HTML page (default: 264 pixels). You can specify the number of pixels as either a number (such as 400) or a string ending in "px" (such as "400px"). Or you can specify a percentage of the size of the parent element, with a string ending in "%" (such as "100%"). Note: To resize the video, adjust the CSS of the subscriber's DOM element (the element property of the Subscriber object) or (if the width is specified as a percentage) its parent DOM element (see Resizing or repositioning a video).
completionHandler function (Optional) A function to be called when the call to the subscribe() method succeeds or fails. 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, defined by the Error class, 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 subscribe() method:
session.subscribe(stream, "subscriber", null, function (error) {
  if (error) {
    console.log(error.message);
  } else {
    console.log("Subscribed to stream: " + stream.id);
  }
});
Returns:
The Subscriber object for this stream. Stream control functions are exposed through the Subscriber object.

unpublish(publisher)

Ceases publishing the specified publisher's audio-video stream to the session. By default, the local representation of the audio-video stream is removed from the web page. Upon successful termination, the Session object on every connected web page dispatches a streamDestroyed event.

To prevent the Publisher from being removed from the DOM, add an event listener for the streamDestroyed event dispatched by the Publisher object and call the preventDefault() method of the event object.

Note: If you intend to reuse a Publisher object to publish to different sessions (or the same session) sequentially, add an event listener for the streamDestroyed event dispatched by the Publisher object (when it stops publishing). In the event listener, call the preventDefault() method of the event object to prevent the Publisher's video from being removed from the page.

Events dispatched:

streamDestroyed (StreamEvent) — The stream associated with the Publisher has been destroyed. Dispatched on by the Publisher on on the Publisher's browser. Dispatched by the Session object on all other connections subscribing to the publisher's stream.

Example
The following example publishes a stream to a session and adds a Disconnect link to the web page. Clicking this link causes the stream to stop being published.
<script>
  var apiKey = ""; // Replace with your API key. See https://tokbox.com/account
  var sessionID = ""; // Replace with your own session ID.
                   // See https://tokbox.com/developer/guides/create-session/.
  var token = ""; // Replace with a generated token.
                  // See https://tokbox.com/developer/guides/create-token/.
  var publisher;
  var session = OT.initSession(apiKey, sessionID);
  session.connect(token, function(error) {
    if (error) {
      console.log(error.message);
    } else {
      // This assumes that there is a DOM element with the ID 'publisher':
      publisher = OT.initPublisher('publisher');
      session.publish(publisher);
    }
  });

  function unpublish() {
    session.unpublish(publisher);
  }
</script>

<body>

    <div id="publisherContainer/>
    <br/>

    <a href="javascript:unpublish()">Stop Publishing</a>

</body>
Parameters:
Name Type Description
publisher Publisher The Publisher object to stop streaming.
See:

unsubscribe(subscriber)

Stops subscribing to a stream in the session. the display of the audio-video stream is removed from the local web page.
Example

The following code subscribes to other clients' streams. For each stream, the code also adds an Unsubscribe link.

var apiKey = ""; // Replace with your API key. See See https://tokbox.com/account
var sessionID = ""; // Replace with your own session ID.
                    // See https://tokbox.com/developer/guides/create-session/.
var token = ""; // Replace with a generated token.
                // See https://tokbox.com/developer/guides/create-token/.
var streams = [];

var session = OT.initSession(apiKey, sessionID);
session.on("streamCreated", function(event) {
    var stream = event.stream;
    displayStream(stream);
});
session.connect(token);

function displayStream(stream) {
    var div = document.createElement('div');
    div.setAttribute('id', 'stream' + stream.streamId);

    var subscriber = session.subscribe(stream, div);
    subscribers.push(subscriber);

    var aLink = document.createElement('a');
    aLink.setAttribute('href', 'javascript: unsubscribe("' + subscriber.id + '")');
    aLink.innerHTML = "Unsubscribe";

    var streamsContainer = document.getElementById('streamsContainer');
    streamsContainer.appendChild(div);
    streamsContainer.appendChild(aLink);

    streams = event.streams;
}

function unsubscribe(subscriberId) {
    console.log("unsubscribe called");
    for (var i = 0; i < subscribers.length; i++) {
        var subscriber = subscribers[i];
        if (subscriber.id == subscriberId) {
            session.unsubscribe(subscriber);
        }
    }
}
Parameters:
Name Type Description
subscriber Subscriber The Subscriber object to unsubcribe.
See:

Events

archiveStarted

Dispatched when an archive recording of the session starts.
See:

archiveStopped

Dispatched when an archive recording of the session stops.
See:

connectionCreated

Dispatched when a new client (including your own) has connected to the session, and for every client in the session when you first connect. (The Session object also dispatches a sessionConnected event when your local client connects.)
See:

connectionDestroyed

A client, other than your own, has disconnected from the session.
See:

cpuPerformanceChanged

The CPU performance state has changed. This can be set to one the following: "nominal", "fair", "serious", or "critical". This is a beta feature.
See:

muteForced

A moderator has forced clients publishing streams to the session to mute audio (the active property of this MuteForcedEvent object is set to true), or a moderator has disabled the mute audio state in the session (the active property of this MuteForcedEvent object is set to false).
See:

sessionConnected

The client has connected to a Vonage Video API session. This event is dispatched asynchronously in response to a successful call to the connect() method of a Session object. Before calling the connect() method, initialize the session by calling the OT.initSession() method. For a code example and more details, see Session.connect().
See:

sessionDisconnected

The client has disconnected from the session. This event may be dispatched asynchronously in response to a successful call to the disconnect() method of the Session object. The event may also be dispatched if a session connection is lost inadvertently, as in the case of a lost network connection.

The default behavior is that all Subscriber objects are unsubscribed and removed from the HTML DOM. Each Subscriber object dispatches a destroyed event when the element is removed from the HTML DOM. If you call the preventDefault() method in the event listener for the sessionDisconnect event, the default behavior is prevented, and you can, optionally, clean up Subscriber objects using your own code.

The reason property of the event object indicates the reason for the client being disconnected.

See:

sessionReconnected

The local client has reconnected to the Vonage Video API session after its connection was lost temporarily. When the connection is lost, the Session object dispatches a sessionReconnecting event, prior to the sessionReconnected event. If the client cannot reconnect to the session, the Session object dispatches a sessionDisconnected event instead of this event.

Any existing publishers and subscribers are automatically reconnected when client reconnects and the Session object dispatches this event.

Any signals sent by other clients while your client was disconnected are received upon reconnecting. By default, signals initiated by the local client while disconnected (by calling the Session.signal() method) are sent when the client reconnects to the Vonage Video API session. You can prevent this by setting the retryAfterReconnect property to false in the signal object you pass into the Session.signal() method.

See:

sessionReconnecting

The local client has lost its connection to a Vonage Video API session and is trying to reconnect. This results from a loss in network connectivity. If the client can reconnect to the session, the Session object dispatches a sessionReconnected event. Otherwise, if the client cannot reconnect, the Session object dispatches a sessionDisconnected event.

In response to this event, you may want to provide a user interface notification, to let the user know that the app is trying to reconnect to the session and that audio-video streams are temporarily disconnected.

See:

signal

A signal was received from the session. The SignalEvent class defines this event object. It includes the following properties:
  • data — (String) The data string sent with the signal (if there is one).
  • from — (Connection) The Connection corresponding to the client that sent the signal.
  • type — (String) The type assigned to the signal (if there is one).

You can register to receive all signals sent in the session, by adding an event handler for the signal event. For example, the following code adds an event handler to process all signals sent in the session:

session.on("signal", function(event) {
  console.log("Signal sent from connection: " + event.from.id);
  console.log("Signal data: " + event.data);
});

You can register for signals of a specified type by adding an event handler for the signal:type event (replacing type with the actual type string to filter on).

See:

streamCreated

A new stream, published by another client, has been created on this session. For streams published by your own client, the Publisher object dispatches a streamCreated event. For a code example and more details, see StreamEvent.
See:

streamDestroyed

A stream from another client has stopped publishing to the session.

The default behavior is that all Subscriber objects that are subscribed to the stream are unsubscribed and removed from the HTML DOM. Each Subscriber object dispatches a destroyed event when the element is removed from the HTML DOM. If you call the preventDefault() method in the event listener for the streamDestroyed event, the default behavior is prevented and you can clean up a Subscriber object for the stream by calling its destroy() method. See Session.getSubscribersForStream().

For streams published by your own client, the Publisher object dispatches a streamDestroyed event.

For a code example and more details, see StreamEvent.

See:

streamPropertyChanged

Defines an event dispatched when property of a stream has changed. This can happen in in the following conditions:

  • A stream has started or stopped publishing audio or video (see Publisher.publishAudio() and Publisher.publishVideo()). Note that a subscriber's video can be disabled or enabled for reasons other than the publisher disabling or enabling it. A Subscriber object dispatches videoDisabled and videoEnabled events in all conditions that cause the subscriber's stream to be disabled or enabled.
  • The videoDimensions property of the Stream object has changed (see Stream.videoDimensions).
  • The videoType property of the Stream object has changed. This can happen in a stream published by a mobile device. (See Stream.videoType.)
See:

signal:type

A signal of the specified type was received from the session. The SignalEvent class defines this event object. It includes the following properties:
  • data — (String) The data string sent with the signal.
  • from — (Connection) The Connection corresponding to the client that sent the signal.
  • type — (String) The type assigned to the signal (if there is one).

You can register for signals of a specified type by adding an event handler for the signal:type event (replacing type with the actual type string to filter on). For example, the following code adds an event handler for signals of type "foo":

session.on("signal:foo", function(event) {
  console.log("foo signal sent from connection " + event.from.id);
  console.log("Signal data: " + event.data);
});

You can register to receive all signals sent in the session, by adding an event handler for the signal event.

See: