Go
Not registered? Sign up!

JavaScript API Examples

Google Translate
JavaScript API Examples

The Flash-based JW Player can be controlled with an extensive JavaScript API (Application Programmers Interface). This page will introduce you to the fundamentals of player scripting and you will find some examples and source code showing the usage. This page contains a list of all examples discussed here, plus some extras.

  1. Prerequisites
  2. A Page with a Player
  3. Placing the Script
  4. Placing the Player
  5. Validating the Embedding
  6. Scriptless Embedding
  7. The Flashvars
  8. The Listeners
  9. Calling the Player
  10. External Control and Listener Feedback

Prerequisites

First of all - you must have the Adobe flash Player browser plugin installed. You can check the flash plugin version at this page: Adobe flash Version Test

Sometimes it is best to un-install an old (faulty) flash plugin, before upgrading to the new version. This Adobe page provides uninstall help: Adobe flash uninstall

Keep your flash plugin updated at all times. Adobe releases new versions often, introducing new features and more importantly, new security upgrades. These security upgrades are extremely important, so again, always make sure to update.

Secondly, - JavaScript must be enabled in your webbrowser. If not, you should look in to the browser options and check "Enable JavaScript".

Third, - The player will play in any flash enabled web browser, but you must have access to webpage or a server to use the API. The JavaScript API only works online on a webpage on a server. This is a security feature of the flash plugin, and can not be changed. Here's more Adobe information on security: Flash Player 9 security white paper.

A Page with a Player

By now you have probably downloaded the JW FLV Media Player package and unpacked the mediaplayer.zip file in to a folder - it should contain the following files:

  1. player.swf (the actual player)
  2. preview.jpg (an optional preview picture)
  3. readme.html (a page showing the player)
  4. swfobject.js (the JavaScript that places the player on the page)
  5. video.flv (a demonstration video)
  6. yt.swf (optional YouTube proxy - extra needed only to play YouTube videos)

If you open the "readme.html" in your favourite webbrowser you should see a page with the JW FLV Media Player showing the "preview.jpg" - if you click the player it should start playing the "video.flv"

You can test now by uploading the above files to your online folder. If you can show the readme.html from your webaddress and the video plays - you are ready to start experimenting with the JW FLV Media Player - JavaScript API

The examples use the SWFObject 2.x JavaScript for the embedding of the player, and to detect if your visitors have the right flash plugin (and JavaScript) installed.Set the minimum flash version in the swfobject code. in these examples it is set to "9.0.115" - flash actionscript3 requires at least "9" and various improvements of the plugin have been made since.

Placing the Script

For the handling of the player you will use HTML - CSS and JavaScript syntax:

Here is the code for a minimal HTML page:


Try this: JW_API_xmpl_0-0-0-0.html
<html>
    <head>
        <title>JW API Example 0-0-0-0 - minimal HTML</title>
    </head>
    <body>
        Hello World
    </body>
</html>
In the <head> there is the <title> that will be shown in the browser titlebar, and in the <body> of the page, some text content: "Hello World"

Next add some CSS to control the layout of the page content:


Try this: JW_API_xmpl_0-0-0.html
<html>
    <head>
        <title>JW API Example 0-0-0 - minimal HTML/CSS</title>
        <style type="text/css">
          #wrapper { position:absolute; left:64px; top:128px; background-color:#CCCC00; }
        </style>
    </head>
    <body>
        <div id="wrapper">Hello Stylesheet World</div>
    </body>
</html>

In the head, a stylesheet is defined with the id "wrapper" and position 64,128 and in the body of the page, the content is wrapped in the <div> stylesheet.

There are now several places that allow the addition of some JavaScript code. But not all the places are equally well suited. A test will show the differences. Note the sequence of the messages that show during the execution of the page.


Try this: JW_API_xmpl_0-0.html
<html>
    <head>
        <title>JW API Example 0-0 - minimal JavaScriptt</title>
        <style type="text/css">
          #wrapper { position:absolute; left:64px; top:128px; background-color:#CCCC00; }
        </style>
        <script type="text/JavaScript"> 
            alert('A - Hello World from the head');
        </script>
    </head>
    <body onload="alert('C - hello world from onload');">
        Hello World<br>
        <script type="text/JavaScript"> 
            alert('B - Hello World from the body');
        </script>
        <a href="JavaScript:alert('Hello World from link');">click for link alert</a>
        <div id="wrapper" onclick="alert('Hello World from onclick');">Click this stylesheet for onclick alert</div>
    </body>
</html>

To permit the page buildup to proceed uninterupted, the choise is to use the "onload" handler. The onload event is triggered last, after the layout of the page have finished building.
By enclosing the alert in a function definition, it can be prevented that the command is executed until this function is explicitely called. This also allows for the transfer of variable values in the function call. Note here how the function doSomething is (re)used by the onload handler and the clicks on the page, and how the different messages are transfered to the function, to be displayed in the alert box.

Try this: JW_API_xmpl_0.html
<html>
    <head>
        <title>JW API Example 0 - JavaScript function</title>
        <style type="text/css">
          #wrapper { position:absolute; left:64px; top:128px; background-color:#CCCC00; }
        </style>
        <script type="text/JavaScript"> 
        function doSomething(theValue) {
            alert('Hello World ' + theValue);
        }
        </script>
    </head>
    <body onload="doSomething('from onload');">
        Hello World<br>
        <a href="JavaScript:doSomething('from link');">click for link alert</a>
        <div id="wrapper" onclick="doSomething('from onclick');">Click this stylesheet for onclick alert</div>
    </body>
</html>

This is the general page and script structure of almost all the collected examples.

Placing the Player

Make the inclusion of the player by using the external JavaScript swfobject.js in the head of the page. Place the loading call to swfobject.js first, and then another script block with the rest of the player-creating script.

The commands to create the player are placed inside the function createPlayer, and the onload handler is set to call this function when the layout has settled. Most of the examples will be based on this code pattern.
Make sure all references to files are set correctly after you copy-paste the code.
Look for "swfobject.js" - "video.flv" and "player.swf" and make sure they are in the correct place.


Try this: JW_API_xmpl_1-1-1-0.html
<html>
    <head>
        <title>JW API Example 1-1-1-0 - JW FLV Media Player</title>
        <style type="text/css">
            #wrapper { position:absolute; left:64px; top:128px; width:320px; height:196px; background-color:#CCCC00; }
        </style>
        <script type="text/JavaScript" src="swfobject.js"></script>
        <script type="text/JavaScript">

        function createPlayer() {
            var flashvars = {
                    file:"video.flv", 
                    autostart:"true"
            }
            var params = {
                    allowfullscreen:"true", 
                    allowscriptaccess:"always"
            }
            var attributes = {
                    id:"player1",  
                    name:"player1"
            }
            swfobject.embedSWF("player.swf", "placeholder1", "320", "196", "9.0.115", false, flashvars, params, attributes);
        }
        </script>
    <head>
    <body onload="createPlayer();">
            <div id="wrapper">
                <div id="placeholder1"></div>
            </div>
    </body>
</html>

"placeholder1" is the identity of the position where the script creates the player. The "wrapper" stylesheet is defined with the same width and height as the player, to reserve space for the player on the page it self, during the layout buildup.

Validating the Embedding

If you care for standards, and want to make the player validate as strict XHTML - you can place the JavaScript functions in a CDATA tag and comments.


Try this: JW_API_xmpl_1-2-0-0.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <title>JW API Example 1-2-0-0 - XHTML Validating JW FLV Media Player</title>
        <style type="text/css">
            #wrapper { position:absolute; left:64px; top:128px; width:320px; height:196px; background-color:#CCCC00; }
        </style>
        <script type="text/JavaScript" src="swfobject.js"></script>
        <script type="text/JavaScript">
        /* <![CDATA[ */
        function createPlayer() {
            var flashvars = {
                    file:"video.flv", 
                    autostart:"true"
            }
            var params = {
                    allowfullscreen:"true", 
                    allowscriptaccess:"always"
            }
            var attributes = {
                    id:"player1",  
                    name:"player1"
            }
            swfobject.embedSWF("player.swf", "placeholder1", "320", "196", "9.0.115", false, flashvars, params, attributes);
        }
        /* ]]> */
        </script>
    </head>
    <body onload="createPlayer();">
            <div id="wrapper">
                <div id="placeholder1"></div>
            </div>
    </body>
</html>

Scriptless Embedding

It is possible to embed the player without swfobject.js - swfobject produces the correct object/embedding code for you, but you can write it your self instead.


Try this: JW_API_xmpl_1-3-1-0.html
<html>
    <head>
        <title>JW API Example 1-3-1-0 - Object/Embed code</title>
        <style type="text/css">
          #wrapper { position:absolute; left:64px; top:128px; width:320px; height:240px; background-color:#FFFFFF; }
        </style>
    </head>
    <body>
        <div id="wrapper">  

            <object id="player1"
                    classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
                    codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9.0.115"                    
                    width="320" height="240">
                <param name=bgcolor value="#FFFFFF">
                <param name=movie value="player.swf">
                <param name=allowfullscreen value="true">
                <param name=allowscriptaccess value="always">
                <param name="flashvars" value="file=video.flv&fullscreen=true&controlbar=bottom">

                <embed name="player1" 
                    type="application/x-shockwave-flash" 
                    pluginspage="http://www.macromedia.com/go/getflashplayer" 
                    width="320" height="240" 
                    bgcolor="#FFFFFF" 
                    src="player.swf"
                    allowfullscreen="true"
                    allowscriptaccess="always"
                    flashvars="file=video.flv&fullscreen=true&controlbar=bottom">
                </embed>
            </object>

        </div>
    </body>
</html>

Some systems will not accept anything but the embed code. So as a last resort you can try the following. Note you have to place both the "name" and the "id" in the embed code, when using the player this way.


Try this: JW_API_xmpl_1-3-2-0.html
<html>
    <head>
        <title>JW API Example 1-3-2-0 - only Embed code</title>
    </head>
    <body>

        <embed name="player1" id="player1"
            type="application/x-shockwave-flash" 
            pluginspage="http://www.macromedia.com/go/getflashplayer" 
            width="320" height="240" 
            bgcolor="#FFFFFF" 
            src="player.swf"
            allowfullscreen="true"
            allowscriptaccess="always"  
            flashvars="file=video.flv&fullscreen=true&controlbar=bottom">
        </embed>

    </body>
</html>

Please also see the Embedding Flash Tutorial for more embedding info, the Adobe page about: Flash Object and Embed tag syntax, and the page about the: Flash Object and Embed tag attributes

In particular note the "wmode" parameter - it can sometimes be useful to set this to "opaque" or "transparent" in order to be able to mask the player or have menus that cover it. (see JW_API_xmpl_7-1-1-0.html for an example of the former)

The Flashvars

Assigning values to the flashvars determines the player functionality and layout. This implies that they can only be set while creating the player. (instantiating) but changing the value of a flashvar is possible by replacing the existing player.

The file flashvar must be set to a filename, or maybe absolute url including the http:// of a media-file or of a playlist that points to mediafiles. (see JW_API_xmpl_3-1-1-1.html for an example of the changing of the file flashvar)

The remaining flashvars are optional and are used for things like autostart or not, hiding the controlbar or placing the playlist to the right or below the display. (see JW_API_xmpl_3-4-1-0.html for an example of the changing of the skin flashvar)

Please make sure to see the wiki page with the list of all the flashvars and their possible values: http://developer.longtailvideo.com/trac/wiki/FlashVars

You can also try some experiments with the Wizard It will produce correct code for your settings

The first few examples of the Example Collection show the various basic layouts of the player

Several of the other examples look very similar when looking at the page. But all the examples are coded to work slightly differently. So make sure to try out, and view and compare the source of the examples. And best try some experiments, change a few of the variables, see what happens...

The Listeners

When the browser has finished executing the creating script, the player calls the function playerReady if provided. This gives the opportunity to set a variable player to contain the player id, for later use when calling the player.

In its simplest form this can look like these lines:
var player = null; 
function playerReady(thePlayer) { player = window.document[thePlayer.id]; }

Now all it takes is the following command to toggle the start/pause of the player:

Try this: JW_API_xmpl_5-1-0-0.html
<a href="JavaScript:player.sendEvent('PLAY')">play/pause toggle</a>

A call to the command player.getPlaylist() returns the data of the full playlist.

The following code shows the playlist data on the page. This is done by looping through the playlist items one by one, and assembling a text string with the data formatted as a html list, which is then displayed on the page.

Try this: JW_API_xmpl_4-2-2-0.html
var player = null;
function playerReady(thePlayer) {
	player = document.getElementById(thePlayer.id);
	printPlaylistData();
}


function printPlaylistData() {
	var plst = null;
	plst = player.getPlaylist();
	if (plst) {
		var txt = '';
		for(var itm in plst) { 
			txt += '<li>'+itm+':</li>';
			txt += '<ul>';
			txt += '<li>'+plst[itm].title+'</li>';
			txt += '<li>'+plst[itm].author+'</li>';
			txt += '<li>'+plst[itm].file+'</li>';
			txt += '</ul><br>';
		}
		var tmp = document.getElementById("plstDat");
		if (tmp) { tmp.innerHTML = txt; }
	} else {
		setTimeout("printPlaylistData()",100);
	}	
}

By including the following function addListeners() and calling it from playerReady - it is possible to tell the player to send data to functions in the script.

The listeners comes in three groups and are invoked with each their command:
  1. addControllerlListeners()
  2. addModelListeners()
  3. addViewListeners()
Make sure to see the complete list of commands in the JavaScript API

Here the "STATE" data from the group addModelListener are assigned to be send to the function stateListener which is supposed to be present.
var player = null;
function playerReady(thePlayer) {
	player = document.getElementById(thePlayer.id);
	addListeners();
}


function addListeners() {
	if (player) { 
		player.addModelListener("STATE", "stateListener");
	} else {
		setTimeout("addListeners()",100);
	}
}

This function can then do what ever required, in response to the changing states of the player. The following code shows the current and previous states on the page and redirects to a new page when the playing has finished.

Try this: JW_API_xmpl_4-3-2-0.html
function stateListener(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
	currentState = obj.newstate; 
	previousState = obj.oldstate; 

	var tmp = document.getElementById("stat");
	if (tmp) { 
		tmp.innerHTML = "current state: " + currentState + 
		"<br>previous state: " + previousState; 
	}

	if ((currentState == "COMPLETED")&&(previousState == "PLAYING")) {
		document.location.href="http://www.longtailvideo.com/players/jw-flv-player/"; 
	}
}

(Possible states are: IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED )

Calling the player

Some of the simple sendEvent calls that the player understand are quite selfexplanatory, such as the commands to "PLAY" - "MUTE" or "STOP" playing.

The example uses a link. It could also be an image, a button or call from function.

Try this: JW_API_xmpl_5-1-0-0.html
<a href="JavaScript:player.sendEvent('MUTE')">mute/sound toggle</a>

Others commands like "LOAD" takes an argument, in this case it is a filename...
(but it is also possible to load a playlist from memory - JW_API_xmpl_5-2-4-0.html )

Try this: JW_API_xmpl_5-2-1-0.html
<a href="JavaScript:player.sendEvent('LOAD', 'video.flv')">load a video</a>

The commands "VOLUME" or "SEEK" also takes arguments, here the position...

Try this: JW_API_xmpl_5-1-0-0.html
<a href="JavaScript:player.sendEvent('SEEK', 10)">seek absolute position (10th. second)</a>

Please note: When seeking/scrubbing in videos:
The player can only stop where the file contain keyframes
For more info on this, please see the tutorial Web Video Compression

Combining External Control and Listener Feedback

Keeping track of listener values makes it simple to make dynamic volume controls or position scrubbers. If a volumeListener is assigned, and a global variable: currentVolume is set with the volume value. Then this variable can simply be used directly in the call, and added to or subtracted from, as required...

Try this: JW_API_xmpl_6-1-0-0.html
var currentVolume = 80; 

var player = null;
function playerReady(thePlayer) {
	player = window.document[thePlayer.id];
	addListeners();
}

function addListeners() {
	if (player) { player.addControllerListener("VOLUME", "volumeListener"); } 
	else { setTimeout("addListeners()",100); }
}

function volumeListener(obj) { currentVolume = obj.percentage; }

And this is how the code for the dynamic volume control call can then look like...
<a href="JavaScript:player.sendEvent('VOLUME', currentVolume+10)">set current volume +10%</a>


Combining a call to getPlaylist() with the ability of the player to load a playlist from memory, give some powerful playlist manipulating and editing possibilities. (load a playlist from memory - JW_API_xmpl_5-2-4-0.html )

Here the playlist is read into the variable currentPlaylist and shown on the page, along with a checkbox for each item. When the link "Load selected Items only." is clicked, the variable currentPlaylist is then read by a loop, and the selected items added to a temporary playlist in memory, and subsequently read into the player with the "load" command. (If the loop counts down the playlist is reversed)

Try this: JW_API_xmpl_6-2-0-0.html
function getPlaylistData() { 
	var plst = null;
	plst = player.getPlaylist();

	if (plst) { 
		currentPlaylist = plst; 

		var txt = ''; 
		for(var i in currentPlaylist) { 
			txt += '<input type="checkbox" id="cb' + i + '" checked="checked" /> &nbsp; ';
			txt += currentPlaylist[i].title;
			txt += '<br />';
		}
		var tmp = document.getElementById("plstDat");
		if (tmp) { tmp.innerHTML = txt; }
	}	
}


function loadCheckedPlaylistData() { 
	if (currentPlaylist) { 
		var j = 0; 
		var lst = new Array();
		for(var i in currentPlaylist) { 
			if(document.getElementById('cb' + i).checked) {
				lst[j] = {
					author:currentPlaylist[i].author,
					description:currentPlaylist[i].description,
					duration:currentPlaylist[i].duration,
					file:currentPlaylist[i].file,
					link:currentPlaylist[i].link,
					image:currentPlaylist[i].image,
					start:currentPlaylist[i].start,
					title:currentPlaylist[i].title,
					type:currentPlaylist[i].type
				}
				j++;
			}

		}
		if(lst.length > 0) { player.sendEvent('LOAD', lst); }
	}	
}

Support and sharing

For more support regarding the JavaScript API, please check the JavaScript section of this site's forum. If you have made any cool demos you want to share, please post those as well!

JW FLV Player

JW FLV Player Download the world's most popular open source player. It supports FLV, MP3, MP4 & AAC; it's Plugin-extensible; and it's fully integrated with our AdSolution. No wonder it's #1.

Monetize Your Video

Monetize Your Video Earn money with ads from LongTail's AdSolution. Watch our demos and sign up now!