Suggestions

close search

Session

Properties Methods Events 

The Session object returned by the OT.initSession() method provides access to much of the OpenTok 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 OpenTok 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; use on() or once() instead.
connect(token, completionHandler) Connects to an OpenTok session.
disconnect() Disconnects from the OpenTok session.
forceDisconnect(connection, completionHandler) Forces a remote connection to leave the session.
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; use off() instead.
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)

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.

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.
See:

connect(token, completionHandler)

Connects to an OpenTok 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 TokBox 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:

disconnect()

Disconnects from the OpenTok 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 created using OT.initPublisher() to publish to different sessions sequentially, call either Session.disconnect() or Session.unpublish(). Do not call both. Then call the preventDefault() method of the Publisher's streamDestroyed event object to prevent the Publisher object from being removed from the page. Be sure to call preventDefault() only if the connection.connectionId property of the Stream object in the event matches the connection.connectionId property of your Session object (to ensure that you are preventing the default behavior for your published streams, not for other streams that you subscribe to).

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);
  }
});

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, properties:Object]):Publisher — In this form, you do not pass a Publisher object into the function. Instead, you pass in a targetElement (the ID of the DOM element that the Publisher will replace) and a properties object that defines options for the Publisher (see OT.initPublisher().) 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 OpenTok 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 c onnection 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.
                    // https://tokbox.com/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)

Deprecated; use off() instead.

Removes an event listener for a specific event.

Throws an exception if the listener name is invalid.

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().)
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 OpenTok 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 OpenTok 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 OpenTok 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 OpenTok 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) — 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 OpenTok 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 Subsciber 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.

    Do not move the publisher element or its parent elements in the DOM heirarchy. Use CSS to resize or reposition the publisher video's element (the element property of the Publisher object) or its parent element (see Resizing or repositioning a video).

  • 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.

    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 (Object) — The preferred resolution of the subscriber's video. 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. You may want to use a resolution for subscribers to a stream that is less important (and smaller) than other streams.

    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:
    • 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 in 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 in 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 OpenTok 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 OpenTok 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) — 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 created using OT.initPublisher() to publish to different sessions sequentially, call either Session.disconnect() or Session.unpublish(). Do not call both. Then call the preventDefault() method of the streamDestroyed or sessionDisconnected event object to prevent the Publisher object from being removed from the page. Be sure to call preventDefault() only if the connection.connectionId property of the Stream object in the event matches the connection.connectionId property of your Session object (to ensure that you are preventing the default behavior for your published streams, not for other streams that you subscribe to).

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:

sessionConnected

The client has connected to an OpenTok 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 disptached if a session connection is lost inadvertantly, 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 OpenTok 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 OpenTok 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 an OpenTok 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 specfied 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 specfied 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: