jQuery OpenTok plugin

Overview

The jQuery OpenTok plugin allows you to easily add OpenTok video sessions to your web page. For information on OpenTok and the OpenTok JavaScript library, see the OpenTok website.

A simple example

This example shows how to connect to an OpenTok session and publish and subscribe to audio-video streams ... all in just a few lines of code.

  1. Include jQuery and the jquery.opentok scripts in your HTML page:
    <head>
        <script type="text/javascript" src="jquery-1.5.2.js"></script>
        <script type="text/javascript" src="jquery.opentok.js"></script>
    </head>
    
  2. Create a JavaScript object that contains settings for the OpenTok session (as defined by the jQuery OpenTok API). In the $(document).ready() handler, pass the options object to the $(element_ID).openTok() method, as in the following:
    <script type="text/javascript">
       var openTokOptions = 
          {
             apiKey: '1127',
             sessionId: '17e55f92e7dedd0e96262432b4c6b66c0141150b',
             connectionToken: 'devtoken'
          }
       
       $(document).ready(function() {
          $('#opentok_container').openTok(openTokOptions);
       });
    </script>
  3. Add the following HTML elements to the page:
    <div id="opentok_container" class="opentok-container">
        <div id="links">
            <a href="#" class="opentok-connect">Connect</a>
            <a href="#" class="opentok-disconnect">Leave</a>
            <a href="#" class="opentok-publish">Publish</a>
            <a href="#" class="opentok-unpublish">Unpublish</a>
        </div>
        <div class="opentok-publisher"></div>
        <div class="opentok-streams"></div>
    </div>

Now you can test the page:

  1. If you are opening the page from the local filesystem (instead of a web server), set Flash Player to grant access to the page:
    1. Open this link in a new browser window: http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html.
    2. In the Alway trust files in these locations list click the Edit locations link and select Add location.
    3. Click Browse for folder, navigate to the folder that contains the HTML file, and then click the Open button.
    4. Click the Always Allow button.
  2. Make sure that you have a webcam connected to your computer and configured to run. Then open the page in a web browser.
  3. Click the Connect link. The page connects to the OpenTok session. The example now connects to a sample OpenTok session. It displays any other video streams in the session (if there are any).
  4. Click the Publish link to publish your webcam's video to the session.
  5. If the Flash Player Settings dialog box is displayed, click the Allow button. This grants the application access to your camera and microphone. The application displays your video and publishes it to the session.
  6. Mute the speaker on your computer. (For this test app, this will prevent audio feedback.)
  7. Copy the URL for this page into the Clipboard.
  8. Open a new browser window, and have it open to the copied URL.

For test purposes, you can view the page in the new browser window on your computer. Or you can open it on another computer (as would happen in a real session.)

The new page now connects to the session. Upon connection the video stream from the other page is displayed on the page and the new published video stream appears on both pages.

The settings used in this example connect to the OpenTok Basic Tuturial session. This simple example also uses many of the default settings for the jQuery OpenTok plugin. The jQuery OpenTok plugin API includes properties for adjusting these settings. For example, you can change the CSS styles that the plugin uses for the user interface controls. For your own application, use a session ID, API key, and token strings that you obtain from OpenTok.

OpenTok plugin API

The OpenTok plugin API provides jQuery access to the OpenTok API. The OpenTok plugin API includes one method: the openTok() method. The rest of the API is defined as the properties of the options parameter of the openTok() method.

The $.openTok() method

The jQuery OpenTok plugin API includes one method: openTok().

openTok()
Initializes an OpenTok session. This method takes one parameter, options, which is required. The method initializes a session based on the properties of the options object.

Calling this method does not connect to the session. To connect to the session, click the HTML element you assign to the connect property of the cssSelector property of the openTokOptions parameter. (See $.openTok() method options.)

This method is chainable.

Example:

var openTokOptions = 
   {
      apiKey: '1127',
      sessionId: '17e55f92e7dedd0e96262432b4c6b66c0141150b',
      connectionToken: 'devtoken',
      cssSelector: {
         connect: '#connectLink',
      }
   }
   
$(document).ready(function() {
  $('#opentok_container').openTok(openTokOptions);
});

$.openTok() method options

The code openTok() method has one parameter: options. The properties of the options object define settings for the OpenTok session, and they specify how the jQuery OpenTok plugin interacts with your page. The options object includes the following properties.

apiKey
The API key (a string) assigned to you by Tokbox. This property is required.

Note: The API key used for the OpenTok tutorial sessions is "1127". You can register for your own OpenTok API key (for use with your sessions) at the TokBox OpenTok developer site.

connectionToken
The connection token string for the Tokbox user.

When you are testing your application, you can simply use 'devtoken' or 'moderator_token' test token strings. However, in production, you must use a token created using the OpenTok server-side libraries. For more information, see Connection token creation in the OpenTok documentation.

If you do not set this property, the jQuery OpenTok plugin uses the 'devtoken' test string by default. The 'devtoken' test token string puts the user in the role of a publisher (which restricts the user using the force unpublish and force disconnect moderation features). The 'moderator_token' test token string puts the user in the role of a moderator, which grants the user full permissions to use all of the OpenTok API.

cssSelector
An object that defines the CSS selectors to use for some of the plugin user interface controls. This object has the following properties (each of them strings), corresponding to the user interface controls:

The following example sets each of these properties. It has the plugin reference DOM elements with specified IDs (such as "connectLink"):

var openTokOptions = 
    {
        apiKey: '1127',
        sessionId: '17e55f92e7dedd0e96262432b4c6b66c0141150b',
        connectionToken: 'devtoken',
        cssSelector: {
            connect: '#connectLink',
            disconnect: '#disconnectLink',
            publish: '#publishLink',
            unpublish: '#unpublishLink',
            streamContainer: '#streamContainer',
            publisherContainer: '#publisherContainer'
        },
    }

$(document).ready(function() {
	$('#opentok_container').openTok(openTokOptions);
}

For this example, add HTML elements that match the IDs of each cssSelector property:

<div id='opentok_container' class="opentok-container">
    <!--div id="opentok_console"></div-->
    <div id="links">
        <a href="#" id="connectLink">Connect</a>
        <a href="#" id="disconnectLink">Leave</a>
        <a href="#" id="publishLink">Publish</a>
        <a href="#" id="unpublishLink">Unpublish</a>
    </div>
    <div id="publisherContainer"></div>
    <div class="streamContainer"></div>
</div>

This property is optional. If you do not set this property, be sure to include elements in your HTML page that use the default style for the controls you wish to enable. For example, the follow code uses HTML elements that match the default cssSelector settings:

<div id="opentok_container" class="opentok-container">
    <div id="links">
        <a href="#" class="opentok-connect">Connect</a>
        <a href="#" class="opentok-disconnect">Leave</a>
        <a href="#" class="opentok-publish">Publish</a>
        <a href="#" class="opentok-unpublish">Unpublish</a>
    </div>
    <div class="opentok-publisher"></div>
    <div class="opentok-streams"></div>
</div>
cssSelectorAncestor
The ID of the parent DOM element that contains the basic controls.

This property is optional. If you do not specify this property, the jQuery OpenTok plugin uses "opentok_container" as the ID of the parent DOM element.

idPrefix
The prefix used for the ID of DIVs the jQuery OpenTok plugin creates for subscriber video streams.

The following shows an example of the DIV for one subscriber when you set this property to "myOtPrefix":

<div id="streams" class="streamContainer">
    <div id="myOtPrefix_opentok_stream_1125674756">
        <div class="opentok-stream">
            <a href="#" class="opentok-mute">Mute</a>
            <a style="display: none;" href="#" class="opentok-unmute">Unmute</a>
            <a href="#" class="opentok-close">Close</a>
            <object data="http://staging.tokbox.com/v0.91.12.201104141540/flash/f_subscribewidget.swf?partnerId=1127" style="outline:none;" id="subscriber_1125674756_1" type="application/x-shockwave-flash" height="198" width="264">
                <param value="always" name="allowscriptaccess">
                <param value="transparent" name="wmode">
                <param value="subscriberId=subscriber_1125674756_1&connectionId=788386f9522b0f5aae3bb9fe08f3c8f07bf2c4d5&sessionId=17e55f92e7dedd0e96262432b4c6b66c0141150b&streamId=1125674756&name=&token=devtoken&simulateMobile=false&width=264&height=198" name="flashvars">
            </object>
        </div>
   </div>
</div>

For each subscriber DIV, the OpenTok plugin assigns an ID that starts with this prefix, followed by "_opentok_stream_", followed by the unique stream ID. For example, if this property is set to ot, a resulting DIV might have the ID "ot_opentok_stream_1125674756".

This property is optional. If you do not specify this property, the jQuery OpenTok plugin uses "ot" as the prefix for the DIV ID.

logLevel
The logging level to use for the OpenTok session. You can set this property to one of the following values:

For example, the following code sets up an OpenTok session and sets the logging level to debug:

var openTokOptions = 
   {
      apiKey: '1127',
      sessionId: '17e55f92e7dedd0e96262432b4c6b66c0141150b',
      connectionToken: 'moderator_token',
      logLevel: $.openTok.logLevel.debug
   }

$(document).ready(function() {
	$('#opentok_container').openTok(openTokOptions);
});

For more information, see the OpenTok documentation for TB.setLogLevel.

sessionId
The session ID (a String) of the OpenTok session. This property is required.

For more information, see the OpenTok documentation on Session creation.

streamCssSelector
An object that defines the CSS styles to use for some of the user interface controls that the plugin adds for each stream it subscribes to. This object has the following properties (each of them strings), corresponding to the user interface controls:

When setting these properties, you must also adjust the streamWrapper property of the options parameter of the $.openTok() method. The streamWrapper property contains the HTML string that the plugin uses to display each subscribed stream:

The following example sets some of these properties. It also adjusts the streamWrapper property:

var openTokOptions = 
    {
        apiKey: '1127',
        sessionId: '17e55f92e7dedd0e96262432b4c6b66c0141150b',
        connectionToken: 'moderator_token',
        streamCssSelector: {
            close: ".example-ot-close",
            mute: ".example-ot-mute",
            unmute: ".example-ot-unmute",
            forceUnpublish: ".example-ot-force-unpublish",
            streamWrapper: ".example-ot-stream",
        },
        streamWrapper: 
             '<div > \
                <div class="example-ot-stream"></div> \
                <br style="clear:both" /> \
                <div> \
                    <a href="#" class="example-ot-mute">Mute</a> \
                    <a href="#" class="example-ot-unmute">Unmute</a> \
                    <a href="#" class="example-ot-force-unpublish">Force Unpublish</a> \
                    <a href="#" class="example-ot-close">Close</a> \
                </div> \
             </div>'
    }

$(document).ready(function() {
   $('#opentok_container').openTok(openTokOptions);
}

Be sure that the CSS selectors you define match the class names in the streamWrapper HTML string.

This property is optional. If you do not set it, the plugin uses the default CSS selectors as listed for each property of this object.

streamWrapper
This defines the HTML to be used to display each OpenTok stream that the session subscribes to. You can set this to either a string (of HTML) or to a function.

If you set this to a function, the function takes two parameters: session (the OpenTok Session object) and stream (the OpenTok Stream object). The function should return the HTML string to use for each stream.

The following code sets the streamWrapper property to a string:

var openTokOptions = 
    {
        apiKey: '1127',
        sessionId: '17e55f92e7dedd0e96262432b4c6b66c0141150b',
        connectionToken: 'devtoken',
        streamWrapper: streamWrapperFn:
            '<div > \
                 <div class="opentok-stream"></div> \
                 <br style="clear:both" /> \
                 <div> \
                    <a href="#" class="opentok-mute-toggle">Mute</a> \
                    <a href="#" class="opentok-unmute">Unmute</a> \
                    <a href="#" class="opentok-force-unpublish">Force Unpublish</a> \
                    <a href="#" class="opentok-close">Close</a> \
                 </div> \
             </div>'
    }

$(document).ready(function() {
   $('#opentok_container').openTok(openTokOptions);
});

The following code sets the streamWrapper property to a function that returns the HTML string:

var openTokOptions = 
    {
        apiKey: '1127',
        sessionId: '17e55f92e7dedd0e96262432b4c6b66c0141150b',
        connectionToken: 'devtoken',
        streamWrapper: streamWrapperFn
    }

function streamWrapperFn(session, stream) {
   return  '<div > \
     <div>Stream: ' + stream.streamId + '</div> \
     <br style="clear:both" /> \
        <div class="opentok-stream"></div> \
        <br style="clear:both" /> \
        <div> \
            <a href="#" class="opentok-mute-toggle">Mute</a> \
            <a href="#" class="opentok-unmute">Unmute</a> \
            <a href="#" class="opentok-force-unpublish">Force Unpublish</a> \
            <a href="#" class="opentok-close">Close</a> \
        </div> \
     </div>';
}

$(document).ready(function() {
   $('#opentok_container').openTok(openTokOptions);
});

The default value defines the following HTML string:

<div class="opentok-stream">
    <a href="#" class="opentok-mute">Mute</a>
    <a href="#" class="opentok-unmute">Unmute</a>
    <a href="#" class="opentok-close">Close</a>
</div>

If you use the default stream, be sure to add CSS definitions for each of the referenced classes. These CSS definitions modify the appearance of the controls in the stream container.

$.openTok properties

The jQuery OpenTok plugin API includes one property.

logLevel
Defines possible values for the logLevel property of the options parameter of the $.openTok() method.

Events

The jQuery OpenTok API has the following events:

These correspond to the events dispatched by the OpenTok Session object. For more information, see the OpenTok documentation on Session events.

To add event listeners for these events, use the jQuery bind() method:

$(document).ready(function() {
   openTok = $('#opentok_container').openTok(openTokOptions);
   openTok.bind($.openTok.event.sessionConnected, connectedHandler);
});

function sessionConnectedHandler(event) {
   var sessionConnectEvent = event.openTok.eventData;
   alert("You are connected to the session. (Number of participants: " + sessionConnectEvent.connections.length + ".)");
}

Note that the OpenTok event object is the openTok.eventData property of the jQuery event object.