JavaScript API for Kaltura Media Players

Printer-friendly version
Audience / Tech Expertise: 

Understanding the JavaScript API for Kaltura Media Players

What is the Kaltura Media Player JavaScript API and why use it?

Kaltura’s flexible media players – the Kaltura HTML5 player and the Flash-based Kaltura Dynamic Player version 3 (KDP3) – provide media online publishing solutions that are easy to use and embed. Kaltura enables you to reach the widest possible end-user audience by using HTML5 in conjunction with KDP3. To learn more about how to embed Kaltura players in your web site and support cross-platform media playback, refer to Embedding Kaltura Media Players in Your Site.

Embedding a Kaltura player is the first step in ensuring a rich user experience. Kaltura's powerful media player JavaScript API enables you to design flexible, multifaceted interaction with the player.

The JavaScript API is a two-way communication channel that lets the player tell you what it is doing and lets you tell the player to do things.

You can use the JavaScript API to:

  • Enable your web page to interact seamlessly with the player
  • Create user interactions with the player
  • Customize aspects of the player

The Basics of the Base Methods

Using the JavaScript API's powerful base methods, you can:

Advanced Uses

There are more advanced things that you can do with the JavaScript API.

  • If you want multiple players on the same web page, you need to configure the jsCallbackReady JavaScript API function. See Managing Multiple Players on the Same Page.
  • You may enrich the user experience and help monetize your site with calls to action and by displaying supplementary material or advertisements at specific points in the video. To support these features, you need to handle the relevant player JavaScript events. See Handling Player JavaScript Events.

In this document you will learn about:

Understanding the JavaScript API Workflow

Questions Answered

How do you work with the JavaScript API?

JavaScript API Workflow

The workflow for the Kaltura media player JavaScript API is:

  1. Enable the JavaScript API.
  2. Receive notification that the player API is ready (jsCallbackReady).
  3. Use the JavaScript API's base methods.

For API documentation, refer to Kaltura Dynamic Player version 3, JavaScript APIs.

Enabling the JavaScript API

Questions Answered

How do you enable the JavaScript API to work with the player?

Enabling the externalInterfaceDisabled Parameter

For a Kaltura player to communicate with the JavaScript API, you enable the Flash's external interface externalInterfaceDisabled parameter. By default, the parameter is disabled.

To enable the externalInterfaceDisabled parameter:

Include the following flashVar in the player embed code: externalInterfaceDisabled=false

Receiving Notification that the Player API Is Ready (jsCallbackReady)

Questions Answered

How do you know that the player is ready to work with the JavaScript API?

Notification of Player Readiness

Before you can use the JavaScript API's base methods, the player has to reach the point in its internal loading sequence when it is ready to interact with your code. The player lets you know that it is ready by calling the jsCallbackReady JavaScript function on the page.

jsCallbackReady is the player's first callback.

The player passes jsCallbackReady an objectId parameter that represents the identifier of the player that is embedded on the page:

function jsCallbackReady(objectId) {
	window.kdp = document.getElementById(objectId);
}	

Kaltura recommends that you place jsCallbackReady in the global scope. This allows easily finding this critical function in the JavaScript code.

Using the JavaScript API's Base Methods

Questions Answered

How do you use the JavaScript API?

Accessing the JavaScript API Base Methods

You can access the entire JavaScript API through methods that enable:

Understanding Events, Notifications, and Commands

KDP3 is based on the PureMVC framework. Significant occurrences in KDP3 are passed as notifications. KDP3 externalizes Flash notifications to be available for JavaScript.

KDP3 fires notifications of passive events. A JavaScript listener (JsListener) detects KDP3 JavaScript notifications. This lets you detect specific events and react to them.

Notifications also are active events that you can use with the sendNotification method to command the player to do something.

Refer to KDP Events for descriptions of passive and active events.

Listening and Responding to Player Events (addJsListener/removeJsListener)

In KDP versions 3.4.10.1 and earlier, JsListeners are executed first and precede the player’s actions. In KDP versions 3.4.10.2 and later, player actions (such as calling the core and plugin handlers) always precede calling the JsListeners.

Using addJsListener

Use the addJsListener method to listen for a specific notification that something happened in the player, such as the video is playing or is paused.

addJsListener Method Syntax

addJsListener("event", "functionName")
  • event is a string that represents the name of the event notification. Enclose the notification name in single or double quotation marks.
  • functionName is a string that represents the name of the listener function to call when the event occurs. Enclose the listener function name in single or double quotation marks, without parentheses.

Sample Code

You may want to enrich the user experience by displaying a video's elapsed time as it plays. Implementing this option requires listening for the video entry's updated time.

To listen for a player entry time being updated:

  1. Pass playerUpdatePlayhead on the notification name parameter in addJsListener.
  2. On your web page, define a JavaScript function that is called when the playerUpdatePlayhead notification is fired in the player (for example, playerUpdatePlayheadHandler).
  3. Pass the JavaScript function name as the listener functionName parameter in addJsListener.
kdp.addJsListener(“playerUpdatePlayhead”, “playerUpdatePlayheadHandler”)
function playerUpdatePlayheadHandler(data, id) {
	// data = the player's progress time in seconds
	// id = the ID of the player that fired the notification
}

Using removeJsListener

Use the removeJsListener method to remove a listener that is no longer needed.

Why Remove a JsListener?

KDP3 accumulates JsListeners. If you add a JsListener for a notification and then add another JsListener for the same notification, the new JsListener does not override the previous one. Both JsListeners are executed in the order in which they are added. To prevent unexpected behavior in your application, Kaltura recommends that you remove unnecessary JsListeners.

When you remove a listener, you must specify the associated function name.

removeJsListener Method Syntax

removeJsListener("event", "functionName")
  • event is a string that represents the name of the event notification. Enclose the notification name in single or double quotation marks.
  • functionName is a string that represents the name of the listener function called when the event occurs. Enclose the listener function name in single or double quotation marks, without parentheses.

Sample Code

To limit listening to a player update event to a single instance:

  1. Insert the addJsListener method to listen for a player update event. For details, see addJsListener sample code.
  2. Insert the removeJsListener method:
  • Pass "playerUpdatePlayhead" on the notification name parameter.
  • Pass the JavaScript function name on the listener functionName parameter.
kdp.addJsListener(“playerUpdatePlayhead”, “playerUpdatePlayheadHandler”)
function playerUpdatePlayheadHandler(data, id) {
	// data = the player's progress time in seconds
	// id = the ID of the player that fired the notification;
}
kdp.removeJsListener(“playerUpdatePlayhead”, “playerUpdatePlayheadHandler”)

Invoking Player Actions (sendNotification)

Use the sendNotification method to create custom notifications that tell the player to do something, such as play, seek, or pause.

sendNotification Method Syntax

sendNotification("command", { optional : data })
  • command is a string that represents the player command. Enclose the command in single or double quotation marks.
  • { optional : data } is an optional  JavaScript Object Notation (JSON) object.

Sample Code

To play a video from a specific point, call the jumpToTime function in the script area of your web page:

  1. Pass the doPlay command on the command parameter in sendNotification.
    Note: doPlay does not require a parameter. You can either use null or omit it.
  2. Pass the doSeek command on the command parameter in sendNotification.
    Specify a timesec parameter in milliseconds from the beginning of the video.
<script language="JavaScript">
	var kdp;
	function jumpToTime(timesec)
	{
		kdp.sendNotification("doPlay");
		// kdp.sendNotification('doPlay', null); // Null parameters are optional

	// Moves to a specific point, defined in seconds from the start of the video
		kdp.sendNotification("doSeek", timesec); 
	}
</script>

Retrieving Information in Runtime (evaluate)

Understanding the evaluate Method

Use the evaluate method to find out something about a player by extracting data from player components.

The evaluate method is valid for any object that KDP3 externalizes for JavaScript, including:

  • uiConf components
    • Buttons and labels are examples of uiConf components.
      Note: Use the component ID to access a uiConf component.
  • Modifiable KDP3 data, such as flashvars and media information
    • Media information is managed as proxy data, known as Value Objects (VO). Refer to KDP-Data-Proxies.
  • The Kaltura Entry Object

    • The Kaltura Entry Object stores all of the textual data related to an entry.

evaluate Method Syntax

evaluate("{object.property.property}")
  • object.property.propertyis the reference to the component object with data that you want to extract. Enclose the reference in curly braces within single or double quotation marks.
    • property references are optional sub-objects and/or properties. property can be an object.

Sample Code

To get the name of an entry from a player so that you can display it:

  1. On your web page, define a function to get the entry name, for example, getName.
  2. Pass the component object reference on the object.property.property parameter in evaluate. Specify the object and property (entry and name) to extract.
  3. Define an alert that displays the extracted data.
function getName() {	
var entry_name = kdp.evaluate('{mediaProxy.entry.name}');
	alert('Entry name: '+entry_name);
}

Changing Player Attributes in Runtime (setKDPAttribute)

Use the setKDPAttribute method to change something about a player by setting player attribute values.

For KDP versions 3.2 and later, use setKDPAttribute. For earlier KDP versions, use setAttribute.

setKDPAttribute Method Syntax

setKDPAttribute("object","property","value")
  • object is a string that represents the object you want to modify. Use standard dot notation to specify sub-objects, for example, configProxy.flashvars.
  • property is the player property that you want to modify.
  • value is the new value that you want to set for the player property.
  • Enclose each parameter – object, property, and value – in single or double quotation marks.
    Note: Do not enclose the parameters in curly braces . (Compare to Retrieving Information in Runtime (evaluate)).

Sample Code

To make a player begin playing automatically, pass the following parameters in setKDPAttribute:

  1. Pass configProxy.flashvars on the object parameter. Define this object using standard dot notation. configProxy holds parameters related to general player configuration.
  2. Pass autoPlay on the property parameter.
  3. Pass true on the value parameter.
kdp.setKDPAttribute("configProxy.flashvars","autoPlay","true")

Understanding JavaScript API Support Differences for Flash and HTML5 Players

Questions Answered

How is JavaScript API support different for Flash-based KDP3 and HTML5 players?

JavaScript API Support Differences

For the APIs (Event Listener and Send Notification) that KDP3 and HTML5 players support, refer to Kaltura KDP API Compatibility.

Managing Multiple Players on the Same Page

Questions Answered

What do you need to do with the JavaScript API to manage multiple players on the same web page?

JavaScript API Considerations in Managing Multiple Players

Kaltura does not recommend using multiple players on the same page. The best practice is to use a single player and display additional videos as thumbnails. When a user selects a thumbnail, the selection loads and plays in the single player.

You can manage multiple players on the same page using either of the following options:

Assign a unique object identifier to each player.

  • In the jsCallbackReady JavaScript API function, add a conditional if statement for each player identifier.
  • For each player, use unique jsCallbackReadyFunc flashVars to call a different jsCallbackReady function for each player. jsCallbackReadyFunc specifies the name of the JavaScript function to call when the player informs the JavaScript interface that it is loaded and ready for interaction.
  1. Define a jsCallbackReady function for each player object identifier.
  2. Pass flashVars in the format jsCallbackReadyFunc = {jsCallbackReadyFuncName} for each player.
  • Replace {jsCallbackReadyFuncName}, including the curly braces, with each unique jsCallbackReady function name.
    Note: Kaltura recommends that you use jsCallbackReady as part of each function name.  

For more information on jsCallbackReady, see Receive notification that the player API is ready (jsCallbackReady).

Handling Player JavaScript Events

Questions Answered

  • What are the benefits of using call to action buttons and cue points that trigger actions?
  • How do you set up custom call to action buttons and implement the actions associated with the buttons?
  • How do you implement actions triggered by cue points?

Understanding Actions Added to the Player

You can use the Kaltura player to enrich the user experience and help monetize your site. Examples include:

  • Customizing call to action buttons
  • Displaying supplementary material or advertisements at specific points in the video

To learn about the benefits and how to support the player JavaScript events that enable these features, see:

Creating Calls to Action Using Custom Buttons

Understanding Calls to Action and Their Benefits

A call to action is a web page element that prompts the user to do something, usually by clicking a button.

Calls to action can help you:

  • Increase engagement in your site
  • Improve your site's conversion rate
  • Promote user interaction
  • Encourage users to return to your site – even when your player is embedded on a different site

Understanding How to Create Call to Action Custom Buttons

You customize call to action buttons for Kaltura players by:

  1. Designing a call to action button in the Kaltura Management Console (KMC)
  2. Defining what happens when a user clicks a call to action button by writing a JavaScript command that you assign to the button

You can add up to five custom buttons.

Each button calls a JavaScript function that you define.

For each button, you can decide where and when the button is displayed, and define a label and tooltip.

The icon for a custom button is a star. You cannot modify the icon.

Designing a Call To Action Button

To learn more about how to configure the player features, refer to the KMC User Manual.

To design a call to action button:

  1. Open the KMC and go to Studio.
  2. Edit an existing player or select a new player.
  3. In the Edit Player or Create New Player window, go to the Features tab and open the Custom Buttons menu.
  4. Select one or more custom buttons and click Options to design the button. You can display your changes in the Preview pane.
  5. Under Options, you can modify the following:
  • Location and Playing States
    • Display the button in the main video area, in the video controls area at the bottom of the player, or both.
    • Define when during the play cycle to display the button in the main video area.
    • Define whether to display the button's icon or label in the video controls area.
  • Label – Define a textual label for the button.
  • Tooltip – Define a tooltip that is displayed when the user hovers over the button in the main video area or the video controls area.
  • Click Apply to review your modifications, and then click Save Changes.
  • For example, you can design a player with a Rent Video button.

    Continue with defining what happens when a user clicks the button.

    Defining What Happens When a User Clicks a Call to Action Button

    To define the action that a user triggers when clicking a custom button:

    In the script area of the web page where you embed the player with the custom button:

    1. Insert the following JavaScript function.
      <script> function customFuncx (entryId){ // Add your custom code here. } </script>
    2.  Replace x in customFuncx with the custom button digit. For example, use customFunc1 for Custom Button 1. See Designing a Call To Action Button.
    3. Where indicated, add JavaScript code that defines an action. For example, create an alert that Custom Button 1 was clicked:
    function customFunc1(entryId)
    {
         alert('Custom button was clicked. Played entryId is '+ entryId );
    }

    To learn more, refer to Integrate KDP on web pages (JavaScript).

    Handling Player Cue Points Using JavaScript

    Understanding Cue Points and Their Benefits

    A cue point is a marker at a precise point of time in a video or audio entry. You may assign metadata to a cue point using the Kaltura API.

    You use a cue point to trigger a time-based event. You can use code cue points and ad cue points.

    You use code cue points to display a file – such as a document, image, or comment – that relates to the content. Code cue points can help you:

    • Enrich the user experience
    • Coordinate related material with specific media content
    • Enable users to skip to specific chapters
    • Share user-generated content at precise points of the playback

    You use ad cue points to insert advertisements at a specified point in the video.

    To learn how to insert advertisements, refer to the KMC User Manual.

    Ad cue points can help you:

    • Generate revenue using midroll advertisements
    • Time ads for specific intervals
    • Coordinate ads with the media content

    In a single video, you may define different types of cue point events and include multiple cue points of each type.

    In the Kaltura Demo Apps, try out the Code Cue Points Demo by selecting the demo from the drop-down menu at the top of the page. The demo lets you create code cue points in a Kaltura video entry and display related files that you tailor for each code cue point.

    Handling Code Cue Points

    To learn about adding and editing cue points in a video, refer to the KMC User Manual.

    Understanding a Code Cue Point Use Case

    The sample code illustrates how to handle code cue points for this use case:

    • A cue point is defined for each chapter.
    • As the video plays and reaches each cue point, the associated chapter name is displayed automatically.
    • When the user selects a chapter name, the player starts playing the video at the selected cue point. 

    Sample Code

    In the script area of the web page where you embed the player, add a JavaScript script:

    1. Insert the addJsListener method (see Using addJsListener) to detect a cue point.
      myPlayer.addJsListener("cuePointReached", "cuePointHandler");
    • Pass "cuePointReached" on the notification name parameter.
    • Pass a function that you define to handle cue points on the listener functionName parameter.
  • Insert your function that handles cue points. Enable the function to receive a cue point identifier.
    var currentCue = null;
    var cuePointHandler = function( qPoint ) {
    	switchActiveCue('cp'+qPoint.cuePoint.id);
    };
  • Insert a function that you define (for example, switchActiveCue) to make a selected cue point active.
    var switchActiveCue = function ( newId ) {
    	if (currentCue != null) currentCue.className = '';
    	currentCue = document.getElementById(newId);
    	currentCue.className = 'selected';
    	console.log(newId);
    }
  • Insert a function  that you define (for example, jumpToTime) to go to a point in the video (defined in milliseconds from the start of the video) and begin playing.
    var jumpToTime = function ( timesec ) {
    	if (myPlayer != null) {
    		myPlayer.sendNotification("doPlay");
    		myPlayer.sendNotification("doSeek", timesec/1000);
    	}
    }

    Use the sendNotification method (see Invoking player actions (sendNotification)).

    • Pass the doPlay command on the command parameter in sendNotification.
    • Pass the doSeek command on the command parameter in sendNotification.  

    This sample requires additional code.

    Populate cue points dynamically in an unordered list.
    For each cue point, define a click event and:

    • Assign the function that starts the video from the cue point (jumpToTime) to the click event.
    • Assign the function that selects the cue point (switchActiveCue) to the click event.
    • Display the cue point time and description.

    Code Cue Point Sample Code

    <script>
    		var jsCallbackReady = function( playerId ) {
    			myPlayer = document.getElementById(playerId);
    			myPlayer.addJsListener("cuePointReached", "cuePointHandler");
    		};
    		
    		var currentCue = null;
    		var cuePointHandler = function( qPoint ) {
    			switchActiveCue('cp'+qPoint.cuePoint.id);
    		};
    		
    		var switchActiveCue = function ( newId ) {
    			if (currentCue != null) currentCue.className = '';
    			currentCue = document.getElementById(newId);
    			currentCue.className = 'selected';
    			console.log(newId);
    		}
    		
    		var jumpToTime = function ( timesec ) {
    			if (myPlayer != null) {
    				myPlayer.sendNotification("doPlay");
    				myPlayer.sendNotification("doSeek", timesec/1000);
    			}
    		}
    		
    </script>

    Best Practices

    Questions Answered

    What best practices does Kaltura recommend for working with the JavaScript API?

    Caching the Player Object in a Global Variable

    Cache a reference to the player object inside a global variable using the following syntax:

    window.kdp = document.getElementById(player_id);

    When you place a reference to the player object inside a variable, you do not need to query the document object model (DOM) each time you do something with the player, such as adding or removing event listeners.

    Kaltura recommends prefixing window. to the variable name to indicate that a global variable is being created.

    Glossary

    Term

    Definition

    Entry

    Kaltura's database and API representation of a content entity and its metadata.

    Entry types include media, video, audio, image, data, mix, document, and playlist.

    Entry metadata includes type, storage location, title, tag, and rating.

    KMC

    Kaltura Management Console. An application for content management, application creation and configuration, content monetization, distribution and syndication, and account management and reporting. The KMC is accessed by Kaltura partner administrators and the various users of a Kaltura account.

     

    (109959 reads)