Suggestions

close search

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

Visit the Vonage API Developer Portal

OT

Methods Events 

The first step in using the OpenTok API is to call the OT.initSession() method. Other methods of the OT object check for system requirements and set up error logging.

Methods

Name Description
(static) addEventListener(type, listener) This method is deprecated.
(static) checkScreenSharingCapability(callback) Checks for support for publishing screen-sharing streams on the client browser.
(static) checkSystemRequirements() → {Number} Checks if the system supports OpenTok for WebRTC.
(static) getActiveAudioOutputDevice() Returns a Promise that resolves the current audio output device.
(static) getAudioOutputDevices() Enumerates the audio output devices (such as speakers) available to the browser.
(static) getDevices(callback) Enumerates the audio input devices (such as microphones) and video input devices (cameras) available to the browser.
(static) getSupportedCodecs() → {Promise} Gets the list of supported codecs for encoding and decoding video streams.
(static) getUserMedia(options) → {Promise} Gets a MediaStream object that uses a microphone and camera as the audio and video source.
(static) hasEndToEndEncryptionSupport() → {Boolean} Whether the client supports end-to-end encryption.
(static) hasMediaProcessorSupport() → {Boolean} Whether the client supports media processors, like video filters.
(static) initPublisher(targetElement, properties, completionHandler) → {Publisher}

Initializes and returns a Publisher object.

(static) initSession(apiKey, sessionId, options) → {Session}

Initializes and returns the local session object for a specified session ID.

(static) log(message) Sends a string to the debugger console.
(static) off(type, handler, context) Removes an event handler.
(static) on(type, handler, context) Adds an event handler function for one or more events.
(static) once(type, handler, context) Adds an event handler function for an event.
(static) registerScreenSharingExtension(kind, id, version) Register an extension for screen-sharing support in an older version of Chrome or Opera.
(static) removeEventListener(type, listener) This method is deprecated.
(static) reportIssue(completionHandler) Report that your app experienced an issue.
(static) setAudioOutputDevice() → {Promise} Sets the new audio output device.
(static) setLogLevel(logLevel) Sets the API log level.
(static) setProxyUrl() Sets the URL of the IP proxy server.
(static) unblockAudio() Causes subscribers' audio to play back in browsers where audio is blocked.
(static) upgradeSystemRequirements() Displays information about system requirements for OpenTok for WebRTC.

(static) addEventListener(type, listener)

This method is deprecated. Use on() or once() instead.

Registers a method as an event listener for a specific event.

The OT object dispatches one type of event — an exception event. The following code adds an event listener for the exception event:

OT.addEventListener("exception", exceptionHandler);

function exceptionHandler(event) {
   alert("exception event. \n  code == " + event.code + "\n  message == " + event.message);
}

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 OT object dispatches the event.
See:

(static) checkScreenSharingCapability(callback)

Checks for support for publishing screen-sharing streams on the client browser. The object passed to the callback function defines whether screen sharing is supported, as well as which screen-sharing sources (application, screen, or window) are supported. It also indicates whether an extension is required, installed, and registered (if needed).

OT.checkScreenSharingCapability(function(response) {
  if (!response.supported || response.extensionRegistered === false) {
    // This browser does not support screen sharing
  } else if (response.extensionInstalled === false) {
    // Prompt to install the extension
  } else {
    // Screen sharing is available.
  }
});

Chrome 72+, Firefox 52+, Safari 13+, Edge 79+, and Opera 59+ have screen-sharing support built-in, with no extension required. (Note that support for the OpenTok plugin for Internet Explorer is removed in OpenTok 2.17.) Screen sharing is not supported in mobile browsers. In Electron, screen sharing is supported if the webPreferences.contextIsolation option of the Electron BrowserWindow is set to false or if the app uses a preload script to access the desktop capturer. (The default value of webPreferences.contextIsolation option is true in Electron 12 and false in previous versions). To publish a screen-sharing video in older versions of Chrome or Opera, the client adds an extension that enables publishing a screen-sharing video stream on your domain. The OpenTok screensharing-extensions sample includes code for creating an extension for screen-sharing support in older versions of Chrome and Opera.

For more information, see the OpenTok Screen Sharing developer guide.

Parameters:
Name Type Description
callback function The callback invoked with the support options object passed as the parameter. This object has the following properties that indicate support for publishing screen-sharing streams in the client:

  • extensionInstalled (Boolean) — In older versions of Chrome and Opera, this is set to true if the extension is installed and registered. In Chrome 72+, Firefox 52+, Safari 13+, Opera 59+, Edge 79+, and Internet Explorer, this property is undefined.
  • supported (Boolean) — Set to true if screen sharing is supported in the browser. Check the extensionRequired property to see if the browser requires an extension for screen sharing.
  • supportedSources (Object) — Deprecated. In older browser versions, you could select a type of screen-sharing source (such as "application", "browser", "screen", or "window" by setting the videoSource property of the options passed into the OT.initPublisher() method. However, in current browsers that support screen sharing, passing in any of these values results in the same behavior — the browser displays a dialog box in which the end user selects the screen-sharing source (which can be the entire screen or a specific window). In Electron, screen sharing captures the entire screen, without prompting the user for permission.

The options parameter also includes the following properties, which apply to screen-sharing support in older versions of Chrome and Opera (in all other browsers these properties are undefined):

  • extensionRequired (String) — Set to "chrome" in older versions of Chrome and Opera, which require a screen-sharing extension to be installed. This property is undefined in other browsers.
  • extensionRegistered (Boolean) — In older versions of Chrome and Opera, this property is set to true if a screen-sharing extension is registered; otherwise it is set to false. In other browsers (which do not require an extension), this property is undefined. Use the OT.registerScreenSharingExtension() method to register a screen-sharing extension in older versions of Chrome or Opera.
See:

(static) checkSystemRequirements() → {Number}

Checks if the system supports OpenTok for WebRTC. Note that this method is called automatically when you call OT.initPublisher() or OT.initSession(), and if the system doesn't support OpenTok, the OpenTok.js library displays a message to the user. Call the OT.checkSystemRequirements() method before calling OT.initPublisher() or OT.initSession() if you do not want the library to display that message.
See:
Returns:
Whether the system supports OpenTok for WebRTC (1) or not (0).

(static) getActiveAudioOutputDevice()

Returns a Promise that resolves the current audio output device.

The method returns a Promise which resolves an object that has two properties: deviceId and label, each of which are strings.

The deviceId property is a unique ID for the device. You can pass the deviceId as the parameter of the OT.setAudioOutputDevice() method. The deviceId property is set to undefined if the user has not previously granted access to a camera and microphone.

The label property identifies the device. The label property is set to an empty string if the user has not previously granted access to a camera and microphone.

Note: Current browser support is for desktop versions of Chrome 49+, Edge 17+, and Opera 36+.

See:

(static) getAudioOutputDevices()

Enumerates the audio output devices (such as speakers) available to the browser.

The method returns a Promise which resolves an array of objects corresponding to available audio output devices. Each object has two properties: deviceId and label, each of which are strings.

The deviceId property is a unique ID for the device. You can pass the deviceId as the parameter of the OT.setAudioOutputDevice() method. The deviceId property is set to undefined if the user has not previously granted access to a camera and microphone. In the case there are no audio output devices available, the property is set to `null`.

The label property identifies the device. The label property is set to an empty string if the user has not previously granted access to a camera and microphone.

Notes::

  • Current browser support is for desktop versions of Chrome 49+, Edge 17+, and Opera 36+.
  • The browser may limit the number of returned audio output devices to one before the user has granted access to a camera or microphone.

See:

(static) getDevices(callback)

Enumerates the audio input devices (such as microphones) and video input devices (cameras) available to the browser.

The array of devices is passed in as the devices parameter of the callback function passed into the method.

Parameters:
Name Type Description
callback function The callback function invoked when the list of devices devices is available. This function takes two parameters:
  • error — This is set to an error object when there is an error in calling this method; it is set to null when the call succeeds.
  • devices — An array of objects corresponding to available microphones and cameras. Each object has three properties: kind, deviceId, and label, each of which are strings.

    The kind property is set to "audioInput" for audio input devices or "videoInput" for video input devices.

    The deviceId property is a unique ID for the device. You can pass the deviceId in as the audioSource or videoSource property of the options parameter of the OT.initPublisher() method.

    The label property identifies the device. The label property is set to an empty string if the user has not previously granted access to a camera and microphone.

Note: The browser may limit the number of returned audio and video input devices to one each before the user has granted access to a camera or microphone.
See:

(static) getSupportedCodecs() → {Promise}

Gets the list of supported codecs for encoding and decoding video streams.

The following example gets the list of supported codecs for encoding and decoding video streams:

(async () => {
  try {
    const supportedCodecs = await OT.getSupportedCodecs();
    if (supportedCodecs.videoEncoders.indexOf('H264') < 0 &&
        supportedCodecs.videoDecoders.indexOf('H264') < 0) {
      // The client does not support encoding or decoding H264.
      // Let's recommend using a different browser.
    }
  } catch(err) {
    console.log(err);
  }
})();

You can use the lists of supported video codecs to determine whether the client supports video, depending on the preferred video codec and the type of session being used. You can set the preferred video codec on the Project page of your Vonage Video API account. In routed sessions (sessions that use the OpenTok Media Router), the preferred video codec is used for all clients in the session. In relayed sessions, clients send streams directly to one another, and each publishing-subscribing pair tries to find a common video codec that they can both use. In this regard, the video codec used by the pair in a relayed session may be different from the preferred video codec setting. For more information see the OpenTok Video codecs developer guide.

Returns:
A promise that is resolved when the list of supported codecs is ready. The promise is resolved (on success) with an object that has two properties: videoDecoders, an array of supported video codecs for decoding, and videoEncoders, an array of supported video codecs for encoding, such as:
{
   videoDecoders: ['H264', 'VP8', 'VP9'],
   videoEncoders: ['H264', 'VP8', 'VP9']
}

The promise is rejected if there is an error in getting the list.

(static) getUserMedia(options) → {Promise}

Gets a MediaStream object that uses a microphone and camera as the audio and video source. This method returns a promise that is resolved when the user has granted permission to use the camera or microphone (or both) and the MediaStream object is available. The promise is rejected if there is an error in getting the media or if the end user denies access to the camera or microphone.

You can use this method to get MediaStreamTrack objects to pass into the audioSource and videoSource options of the OT.initPublisher() method. For example, call this method to get a MediaStream that uses the microphone and camera as the audio and video sources. Then you can call getVideoTracks()[0] on the MediaStream object to get a video MediaStreamTrack object for the camera's video. You can then add the video MediaStreamTrack as a source for an HTML Video element, draw that Video element into an HTML Canvas element, and apply video filters or effects to the Canvas. Then you can call the captureStream() method of the HTMLCanvasElement object to get a MediaStream object and call getVideoTracks()[0] on the MediaStream object to get a video MediaStreamTrack object (with the video filters or effects applied). Finally, you can use the video MediaStreamTrack object as the videoSource property of the options you pass into OT.initPublisher(). The OpenTok Publisher will use the video track (with the filters and effects applied) as the video source.

Parameters:
Name Type Description
options Object

(optional) Defines settings for the MediaStream object. The options are the same as those defined for the OT.initPublisher() method. However, only the following properties apply for OT.getUserMedia():

  • audioSource
  • autoGainControl
  • disableAudioProcessing
  • echoCancellation
  • enableStereo
  • facingMode
  • frameRate
  • maxResolution
  • noiseSuppression
  • resolution
  • videoSource

See:
Returns:
A promise that is resolved when the user has granted permission to use the camera or microphone (or both) and the MediaStream object is available. The promise is rejected if there is an error in getting the media, if the end user denies access to the camera or microphone, or if the method is called on Internet Explorer.

(static) hasEndToEndEncryptionSupport() → {Boolean}

Whether the client supports end-to-end encryption.

The following example enables the end-to-end encryption, if supported by the client:

// Publish in a session with end-to-end encryption, if supported
if (OT.hasEndToEndEncryptionSupport()) {
  session.publish(publisher, error) = {
    ...
  });
}
See:
Returns:
Whether the client supports end-to-end encryption (true), or not (false).

(static) hasMediaProcessorSupport() → {Boolean}

Whether the client supports media processors, like video filters.

The following example enables the background blur filter, if supported by the client:

// Add background blur, if supported
if (OT.hasMediaProcessorSupport()) {
  publisherOptions.videoFilter = {
    type: 'backgroundBlur',
  };
}

const publisher = OT.initPublisher(publisherOptions);
See:
Returns:
Whether the client supports media processors (true), like video filters, or not (false).

(static) initPublisher(targetElement, properties, completionHandler) → {Publisher}

Initializes and returns a Publisher object. You can then pass this Publisher object to Session.publish() to publish a stream to a session.

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.

Parameters:
Name Type Description
targetElement Object (Optional) The DOM element or the id attribute of the existing DOM element used to determine the location of the Publisher 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.

The application throws an error if an element with an ID set to the targetElement value does not exist in the HTML DOM.

properties Object (Optional) This object contains the following properties (each of which are optional):

  • audioBitrate (Number) — The desired bitrate for the published audio, in bits per second. The supported range of values is 6,000 - 510,000. (Invalid values are ignored.) Set this value to enable high-quality audio (or to reduce bandwidth usage with lower-quality audio).

    The following are recommended settings:

    • 8,000 - 12,000 for narrowband (NB) speech
    • 16,000 - 20,000 for wideband (WB) speech
    • 28,000 - 40,000 for full-band (FB) speech
    • 48,000 - 64,000 for full-band (FB) music

    The default value is 40,000.

    Currently, this setting is not supported in streams published in Firefox.

  • audioFallback (Object) — An object containing properties that defines whether the stream will use the audio-fallback feature. The audioFallback object includes the following properties:
    • publisher (Boolean) — Whether the stream will use the publisher audio-fallback feature (true) or not (default false). The publisher audio-fallback feature is available in both routed sessions (sessions that uses the OpenTok Media Router) and relayed sessions. With the publisher audio-fallback feature enabled, when it is determined that a Publisher's quality has degraded significantly, it disables the video in that publisher in order to preserve audio quality. For more information, see the Publisher videoDisabled, videoDisableWarning, videoDisableWarningLifted, and videoEnabled events.

      This is a beta feature.

    • subscriber (Boolean) — Whether the stream will use the subscriber audio-fallback feature (true) or not (false). The audio-fallback feature is available in sessions that use the OpenTok Media Router. With the audio-fallback feature enabled (the default), when the server determines that a stream's quality has degraded significantly for a specific subscriber, it disables the video in that subscriber in order to preserve audio quality. For streams that use a camera as a video source, the default setting is true (the audio-fallback feature is enabled). The default setting is false (the audio-fallback feature is disabled) for screen-sharing streams, which have the videoSource property set to "application", "screen", or "window" in the OT.initPublisher() options. For more information, see the Subscriber videoDisabled event and the OpenTok Media Router and media modes.
  • audioFallbackEnabled (Boolean) — Whether the stream will use the audio-fallback feature (true) or not (false). The audio-fallback feature is available in sessions that use the OpenTok Media Router. With the audio-fallback feature enabled (the default), when the server determines that a stream's quality has degraded significantly for a specific subscriber, it disables the video in that subscriber in order to preserve audio quality. For streams that use a camera as a video source, the default setting is true (the audio-fallback feature is enabled). The default setting is false (the audio-fallback feature is disabled) for screen-sharing streams, which have the videoSource property set to "application", "screen", or "window" in the OT.initPublisher() options. For more information, see the Subscriber videoDisabled event and the OpenTok Media Router and media modes.

    Note that this property will be deprecated in the future. Use the audioFallback parameter instead.

  • audioSource (String, MediaStreamTrack, Boolean, or null) — The ID of the audio input device (such as a microphone) to be used by the publisher. You can obtain a list of available devices, including audio input devices, by calling the OT.getDevices() method. Each device listed by the method has a unique device ID. If you pass in a device ID that does not match an existing audio input device, the call to OT.initPublisher() fails with an error (error code 1500, "Unable to Publish") passed to the completion handler function.

    If you set this property to null or false, the browser does not request access to the microphone, and no audio is published.

    You can also set this property to an audio MediaStreamTrack object. This lets you use the object as the audio source for the published stream. For example, you can get an array of audio MediaStreamTrack objects from the audioTracks property of an HTMLMediaElement object. Or you can call the getLocalStreams() or getRemoteStreams() method of an RTCPeerConnection object to get an array of MediaStream objects, and then call the getAudioTracks() method of one of the MediaStream objects to get an audio MediaStreamTrack object.

  • autoGainControl (Boolean) — Whether to enable automatic gain control for the published audio. You may want to set this to false when publishing high-quality audio (by setting the audioBitrate property of the OT.initPublisher() options). The default value is true. This setting is ignored if you set disableAudioProcessing to true (which disables echo cancellation, automatic gain control, and noise suppression for the published stream).
  • disableAudioProcessing (Boolean) — Whether to disable echo cancellation, automatic gain control, and noise suppression for the published audio. You may want to set this to true when publishing high-quality audio (by setting the audioBitrate property of the OT.initPublisher() options). The default value is false.
  • echoCancellation (Boolean) — Whether to enable echo cancellation for the published audio. You may want to set this to false when publishing high-quality audio (by setting the audioBitrate property of the OT.initPublisher() options). The default value is true. This setting is ignored if you set disableAudioProcessing to true (which disables echo cancellation, automatic gain control, and noise suppression for the published stream).
  • enableStereo (Boolean) — Whether to publish stereo audio. The default value is false.

    Note: Some browsers (such as Chome 73+) do not support echo cancellation for stereo audio (see this Chrome issue report).

  • enableDtx (Boolean) — Whether to enable Opus DTX. The default value is false. Setting this to true can reduce bandwidth usage in streams that have long periods of silence.
  • facingMode (String) — The preferred camera position to use for the video source. Generally, this setting only applies to mobile devices. This can be set to one of the following values:

    • "user" — The front-facing camera.
    • "environment" — The back camera.
    • "left" — The camera facing the user but to the left (uncommon).
    • "right" — The camera facing the user but to the right (uncommon).

  • 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 publishing a camera feed.
    • "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.
  • frameRate (Number) — The desired frame rate, in frames per second, of the video. Valid values are 30, 15, 7, and 1. The published stream will use the closest value supported on the publishing client. The frame rate can differ slightly from the value you set, depending on the browser of the client. And the video will only use the desired frame rate if the client configuration supports it.

    If the publisher specifies a frame rate, the actual frame rate of the video stream is set as the frameRate property of the Stream object, though the actual frame rate will vary based on changing network and system conditions. If the developer does not specify a frame rate, this property is undefined. Also, if the video source is a video MediaStreamTrack object (see the videoSource), this value is ignored and the frame rate is defined by the MediaStreamTrack object, which you can get by calling the getConstraints() method of the MediaStreamTrack object.

    For sessions that use the OpenTok Media Router (sessions with the media mode set to routed, lowering the frame rate proportionally reduces the maximum bandwidth the stream uses. However, in sessions with the media mode set to relayed, lowering the frame rate does not reduce the stream's bandwidth.

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

  • height (Number or String) — The desired initial height of the displayed Publisher 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 publisher video, adjust the CSS of the publisher's DOM element (the element property of the Publisher object) or (if the height is specified as a percentage) its parent DOM element (see Resizing or repositioning a video).
  • initials (String) — The initials for this stream. These initials are shown as centered, capitalized text in each Publisher and Subscriber view when the video is disabled and no backgroundImageURI is set. If backgroundImageURI is set, it takes precedence and is displayed instead of the initials.

    The initials are also set as the initials property of the Stream object.

    Any one or two-character string (of any case) will be acceptable. If invalid initials are used, then no error will be thrown and initials won't be set.

  • 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 Publisher object is undefined. Instead, the Publisher 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 Publisher'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 (or object) element 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 Publisher object will be inserted in the HTML DOM. See the targetElement parameter. This string can have the following values:

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

  • maxResolution (Object) — Sets the maximum resolution to stream. This setting only applies to when the videoSource property is set to "application", "screen", or "window" (when the publisher is screen-sharing). The resolution of the stream will match the captured screen region unless the region is greater than the maxResolution setting. Set this to an object that has two properties: width and height (both numbers). The maximum value for each of the width and height properties is 1920, and the minimum value is 10.
  • mirror (Boolean) — Whether the publisher's video image is mirrored in the publisher's page. The default value is true (the video image is mirrored), except for a screen-sharing video (when the videoSource property is set to "application", "screen", or "window" (in which case the default is false). This property does not affect the display on subscribers' views of the video.
  • name (String) — The name for this stream. The name appears at the bottom of Subscriber videos. The default value is "" (an empty string). Setting this to a string longer than 1000 characters results in an runtime exception.
  • noiseSuppression (Boolean) — Whether to enable noise suppression for the published audio. You may want to set this to false when publishing high-quality audio (by setting the audioBitrate property of the OT.initPublisher() options). The default value is true. This setting is ignored if you set disableAudioProcessing to true (which disables echo cancellation, automatic gain control, and noise suppression for the published stream).
  • publishAudio (Boolean) — Whether to initially publish audio for the stream (default: true). This setting applies when you pass the Publisher object in a call to the Session.publish() method.
  • publishVideo (Boolean) — Whether to initially publish video for the stream (default: true). This setting applies when you pass the Publisher object in a call to the Session.publish() method.
  • publishCaptions (Boolean) — Whether to initially publish captions for the stream (default: false). This setting applies when you pass the Publisher object in a call to the Session.publish() method. This property will have no effect if captions have not been enabled at the session level. For more information, see the Live Captions developer guide.
  • resolution (String) — The desired resolution of the video. The format of the string is "widthxheight", where the width and height are represented in pixels. Valid values are "1920x1080", "1280x720", "640x480", and "320x240". The published video will only use the desired resolution if the client configuration supports it. Some browsers and clients do not support each of these resolution settings.

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

    If you do not specify a resolution, the browser uses the camera's default resolution. Most physical cameras have a default resolution of 640x480, but other cameras, in particular virtual cameras, have different default resolutions. If the client system cannot support the resolution you request, the stream will use the next largest setting supported.

    The actual resolution used by the Publisher is returned by the videoHeight() and videoWidth() methods of the Publisher object. The actual resolution of a Subscriber video stream is returned by the videoHeight() and videoWidth() properties of the Subscriber object. These may differ from the values of the resolution property passed in as the properties property of the OT.initPublisher() method, if the browser does not support the requested resolution, this value is ignored. Also, if the video source is a video MediaStreamTrack object (see the videoSource), this value is ignored and the resolution is defined by the MediaStreamTrack object, which you can get by calling the getConstraints() method of the MediaStreamTrack object.

  • scalableScreenshare (Boolean) — Whether to allow use of scalable video for a publisher that has the videoSource set to "screen" (true) or not (false, the default).
  • scalableVideo (Boolean) — Whether to allow (true, the default) or disable (false) scalable video for the publisher. This only applies in a routed session (one that uses the OpenTok Media Router). Note: By default, scalable video is disabled in screen-sharing videos. You can set the scalableScreenshare option to true to enable scalable video for screen-sharing streams. However, setting scalableVideo to false disables scalable video for any video source (and the scalableScreenshare setting is ignored for screen-sharing streams).
  • showControls (Boolean) — Whether to display the built-in user interface controls (default: true) for the Publisher. These controls include the name display, the audio level indicator, and the microphone control button. 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 Publisher. 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).
    • archiveStatusDisplayMode (String) — How to display the archive status indicator. Possible values are: "auto" (the indicator is displayed when the session is being recorded), "off" (the indicator is not displayed). If you disable the archive status display indicator, you can display your own user interface notifications based on the archiveStarted and archiveStopped events dispatched by the Session object.
    • 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 publishVideo(false) on the Publisher 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 Publisher.getImgData() method. (For example, you could set the property to a value returned by calling getImgData() on a previous Publisher 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 microphone 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 the Publisher. 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 Publisher 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".

      This is a beta feature.

  • videoContentHint (String) — Sets the content hint of the the video track of the publisher's stream. This allows browsers to use encoding or processing methods more appropriate to the type of content. You can set this to one of the following values:

    • "" — No hint is provided (the default).
    • "motion" — The track should be treated as if it contains video where motion is important. For example, you may use this setting for a screen-sharing stream that contains video.
    • "detail" — The track should be treated as if video details are extra important. For example, you may use this setting for a screen-sharing stream that contains text content, painting, or line art.
    • "text" — The track should be treated as if text details are extra important. For example, you may use this setting for a screen-sharing stream that contains text content.

    With the "text" and "detailed" content hints, the browser attempts to maintain high resolution, even if it must reduce the video frame rate. For the "motion" content hint, the browser reduces resolution to prevent the frame rate from stalling.

    You can read more about these options in the W3C Working Draft. You may want to set the video content hint to optimize performance for screen-sharing videos. For example, you can set it to "text" when sharing a screen that contains a lot of text (such as a slideshow).

    Chrome 60+, Safari 12.1+, Edge 79+, and Opera 47+ support video content hints.

    Also see the Publisher.setVideoContentHint() method and the developer guide topic on this feature.

  • videoFilter (Object) — An object containing properties that define the video filter to be applied to the Publisher's video stream. The following filters are supported:
    • Background blur filter — Set the type property of the object to "backgroundBlur".

      A background blur filter object includes an additional blurStrength property, which defines the blur radius and is optional. Set this to either "low" or "high" (the default).

    • Background replacement filter — Set the type property of the object to "backgroundReplacement".

      A background replacement filter object includes an additional backgroundImgUrl property, which defines the URL of the background image to use. Also accepted are image BLOBs (a Base64-encoded string of image data). The following image formats are supported: BMP, PNG, JPEG, and GIF.

      The background image is resized to match the dimensions of the publisher's video. For best results, use an image that has the same dimensions (or at least the same aspect ratio) as the published video. Set the mirror option to false when calling the OT.initPublisher() method to have the background image appear in the correct orientation (not mirrored) in the publisher's page.

    Note: Video filters are only supported in recent versions of Chrome, Electron, Opera, and Edge. They are not supported in other (non-Chromium-based) browsers or on iOS. You can check if the client supports this feature by calling the OT.hasMediaProcessorSupport() method.

    You can change the video filter by calling the Publisher.applyVideoFilter() method. You can remove the video filter by calling the Publisher.clearVideoFilter() method.

  • videoSource (String, MediaStreamTrack, Boolean, or null) — The ID of the video input device (such as a camera) to be used by the publisher. You can obtain a list of available devices, including video input devices, by calling the OT.getDevices() method. Each device listed by the method has a unique device ID. If you pass in a device ID that does not match an existing video input device, the call to OT.initPublisher() fails with an error (error code 1500, "Unable to Publish") passed to the completion handler function.

    If you set this property to null or false, the browser does not request access to the camera, and no video is published. In a voice-only call, set this property to null or false for each Publisher.

    To publish a screen-sharing stream, set this property to "screen". In older browser versions, you could also pass in "application" or "window" to specify a type of screen-sharing source. However, in current browsers that support screen sharing, passing in any of these values results in the same behavior — the browser displays a dialog box in which the end user selects the screen-sharing source (which can be the entire screen or a specific window). In Electron, screen sharing captures the entire screen, without prompting the user for permission. For screen-sharing streams, the following are default values for other properties: audioFallbackEnabled == false, maxResolution == {width: 1920, height: 1920}, mirror == false, scaleMode == "fit". Also, the default scaleMode setting for subscribers to the stream is "fit". In Safari, initializing a screen-sharing publisher without a user gesture handler may throw an InvalidAccessError error.

    You can also set this property to a video MediaStreamTrack object. This lets you use the MediaStreamTrack object as the video source for the published stream. For example, you can get a CanvasCaptureMediaStream object by calling the captureStream() method of a HTMLCanvasElement, and then you can call the getVideoTracks() method of the CanvasCaptureMediaStream object to get a video MediaStreamTrack object. Or you can get an array of video MediaStreamTrack object from the videoTracks property of an HTMLMediaElement object. Or you can call the getLocalStreams() or getRemoteStreams() method of an RTCPeerConnection object to get an array of MediaStream objects, and then call the getVideoTracks() method of one of the MediaStream objects to get an array of video MediaStreamTrack objects. Note that by default the publisher uses a microphone as the audio source, so be sure to set the audioSource option if you want to use a MediaStreamTrack as the audio source or if you do not want to publish an audio track. The default mirror setting for a Publisher with a MediaStreamTrack video source is false. You can also call OT.getUserMedia() to get a MediaStream object that uses the microphone and camera as the audio and video sources.

  • width (Number or String) — The desired initial width of the displayed Publisher 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 publisher video, adjust the CSS of the publisher's DOM element (the element property of the Publisher 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 method succeeds or fails in initializing a Publisher object. This function takes one parameter — error. On success, the error object is set to null. On failure, the error object has two properties: code (an integer) and message (a string), which identify the cause of the failure. The method succeeds when the user grants access to the camera and microphone. The method fails if the user denies access to the camera and microphone. The completionHandler function is called before the Publisher dispatches an accessAllowed (success) event or an accessDenied (failure) event.

The following code adds a completionHandler when calling the OT.initPublisher() method:

var publisher = OT.initPublisher('publisher', null, function (error) {
  if (error) {
    console.log(error);
  } else {
    console.log("Publisher initialized.");
  }
});
See:
Returns:
The Publisher object.

(static) initSession(apiKey, sessionId, options) → {Session}

Initializes and returns the local session object for a specified session ID.

You connect to an OpenTok session using the connect() method of the Session object returned by the OT.initSession() method. Note that calling OT.initSession() does not initiate communications with the cloud. It simply initializes the Session object that you can use to connect (and to perform other operations once connected).

Note that you can initialize only one Session object per session ID. Calling OT.initSession() a second time with the same session ID returns the previously created Session object. However, you can initialize multiple Session objects for different sessions (with different session IDs) to connect to multiple sessions.

When the client disconnects from the session (and the session dispatches a sessionDisconnected event), you can reuse the Session object to reconnect to the session. However, the Session object will retain any existing event handlers attached to it. You can remove all event handlers by calling the off() method of the Session object (passing in no parameters).

For an example, see Session.connect().

Parameters:
Name Type Description
apiKey String Your OpenTok API key (see your Vonage Video API account page).
sessionId String The session ID identifying the OpenTok session. For more information, see Session creation.
options Object An object that includes optional options for initializing the session. This object includes the following properties:
  • connectionEventsSuppressed — (Boolean) Set this property to true to support large interactive video sessions. This prevents the Session object from dispatching connectionCreated and connectionDestroyed events when other clients connect to or disconnect from the session. (Also, the OpenTok server does not send these events to the web client.) For more information, see Suppressing connection events in the OpenTok developer guides.
  • ipWhitelist — (Boolean) This is available as an add-on feature. Set this to true if IP white listing is enabled for your project. The default value is false.
  • iceConfig — (Object) This feature is part of the configurable TURN add-on feature.
  • encryptionSecret — (String) This is the initial encryption secret used by the end-to-end encryption feature. See the developer guide.
Returns:
The session object through which all further interactions with the session will occur.

(static) log(message)

Sends a string to the debugger console. However, the function only logs to the console if you have set the log level to OT.LOG or OT.DEBUG, by calling OT.setLogLevel(OT.LOG) or OT.setLogLevel(OT.DEBUG).
Parameters:
Name Type Description
message String The string to log.
See:

(static) off(type, handler, context)

Removes an event handler.

Pass in an event name and a handler method, the handler is removed for that event:

OT.off("exceptionEvent", exceptionEventHandler);

If you pass in an event name and no handler method, all handlers are removed for that events:

OT.off("exceptionEvent");

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 matching handlers:

OT.off(
  {
    exceptionEvent: exceptionEventHandler
  },
  this
);
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 "eventName1 eventName2 eventName3". 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. 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.
See:

(static) on(type, handler, context)

Adds an event handler function for one or more events.

The OT object dispatches one type of event — an exception event. The following code adds an event listener for the exception event:

OT.on("exception", 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:

OT.on("exception",
  function (event) {
    // This is the event handler.
  }),
  session
);

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

(static) once(type, handler, context)

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

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

OT.once("exception", function (event) {
  console.log(event);
}

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

OT.once("exception",
  function (event) {
    // This is the event handler.
  },
  session
);

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:

OT.once(
  {exeption: function (event) {
    // This is the event handler.
    }
  },
  session
);
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:

(static) registerScreenSharingExtension(kind, id, version)

Register an extension for screen-sharing support in an older version of Chrome or Opera.

Note: A screen-sharing extension is not required in Chrome 72+ or Opera 59+. The end user is prompted to grant access to the screen, just as they would be when granting access to a camera. You only need a screen-sharing extension for older versions of Opera and Chrome.

Use the OT.checkScreenSharingCapability() method to check if an extension is required, registered, and installed.

The OpenTok screensharing-extensions repo includes code for creating an extension for screen-sharing support.

Parameters:
Name Type Description
kind String Set this parameter to "chrome". Currently, you can only register a screen-sharing extension for older versions of Chrome and Opera.
id String The ID for your screen-sharing extension. You can find this ID at chrome://extensions.
version Number The version of the screen-sharing extension from the screensharing-extensions repo. Set this if you are using version 2 or later. For example, if you are using version 2, set this to 2. With version 2, the client can use the extension immediately after installing it, without reloading the page.
See:

(static) removeEventListener(type, listener)

This method is 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.
See:

(static) reportIssue(completionHandler)

Report that your app experienced an issue. You can use the issue ID with Inspector or when discussing an issue with the Vonage API support team.
Parameters:
Name Type Description
completionHandler function A function that is called when the call to this method succeeds or fails. This function has two parameters. The first parameter is an Error object that is set when the call to the reportIssue() method fails (for example, if the client is not connected to the network) or null when the call to the reportIssue() method succeeds. The second parameter is set to the report ID (a unique string) when the call succeeds.

(static) setAudioOutputDevice() → {Promise}

Sets the new audio output device.

The method returns a Promise which resolves when the operation completes successfully. If there is an error, the promise is rejected.

Note: Current browser support is for desktop versions of Chrome 49+, Edge 17+, and Opera 36+.

See:
Returns:
A promise that resolves when the operation completes successfully. If there is an error, the promise is rejected.

(static) setLogLevel(logLevel)

Sets the API log level.

Calling OT.setLogLevel() sets the log level for runtime log messages that are the OpenTok library generates. The default value for the log level is OT.ERROR.

The OpenTok JavaScript library displays log messages in the debugger console (such as Firebug), if one exists.

The following example logs the session ID to the console, by calling OT.log(). The code also logs an error message when it attempts to publish a stream before you have connected to the session (by calling Session.connect()).

OT.setLogLevel(OT.LOG);
session = OT.initSession(sessionId);
OT.log(sessionId);
publisher = OT.initPublisher("publishContainer");
session.publish(publisher);
Parameters:
Name Type Description
logLevel Number The degree of logging desired by the developer:

  • OT.NONE — API logging is disabled.
  • OT.ERROR — Logging of errors only.
  • OT.WARN — Logging of warnings and errors.
  • OT.INFO — Logging of other useful information, in addition to warnings and errors.
  • OT.LOG — Logging of OT.log() messages, in addition to OpenTok info, warning, and error messages.
  • OT.DEBUG — Fine-grained logging of all API actions, as well as OT.log() messages.

See:

(static) setProxyUrl()

Sets the URL of the IP proxy server. With the IP proxy feature, the client routes all internet traffic (except for media streams) via your proxy server.

You must call this method before calling any other OpenTok methods. This ensures that the proxy server is used for OpenTok traffic. Otherwise, the call fails, and the OT object dispatches an exception event. The OT object also dispatches an exception event if you call this method after having previously called it.

This is available as an add-on feature. For more information, see the IP proxy developer guide.

(static) unblockAudio()

Causes subscribers' audio to play back in browsers where audio is blocked. You must call this method in response to an HTML element dispaching a click event.

You only need to call this method if you disable display of the Subscriber's default audio playback icon (by setting the style.audioBlockedDisplayMode property of the options parameter of the Session.subscribe() method). You may call this method in response to the user clicking an HTML element that you display on the page.

The Subscriber dispatches an audioBlocked event if audio is blocked. In response to that event, you can display a UI element to notify the end user to respond to playback subscriber audio. Call the OT.unblockAudio() method in response to the user clicking a DOM element.

Note: Subscriber audio is also unblocked automatically if the local client gains access to the camera or microphone (for instance, in response to a successful call to OT.initPublisher()).

See:
Returns:
Promise The promise resolves if audio playback succeeds on all blocked subscribers. The promise is rejected if playback fails. See Error for details.

(static) upgradeSystemRequirements()

Displays information about system requirements for OpenTok for WebRTC. This information is displayed in an iframe element that fills the browser window.

Note: this information is displayed automatically when you call the OT.initSession() or the OT.initPublisher() method if the client does not support OpenTok for WebRTC.

See:

Events

exception

Dispatched by the OT class when the app encounters an exception. Note that you set up an event handler for the exception event by calling the OT.on() method.
See: