This document provides reference information for the YouTube JavaScript player API.
The JavaScript API allows users to control the YouTube embedded video players via JavaScript. Calls can be made to play, pause, seek to a certain time in a video, set the volume, mute the player, and other useful functions.
The end user must have Flash Player 8 or higher installed to view everything correctly. Because of this requirement, we suggest using SWFObject to embed the SWF and detect the user's Flash Player version.
Note: To test any of these calls, you must have your file running on a webserver, as the Flash player restricts calls between local files and the internet.
To enable the JavaScript API, you must pass the URL parameter enablejsapi=1 in the URL of the player you wish to control. For example, you'd want to use the following URL to embed the SWF.
http://www.youtube.com/v/VIDEO_ID&enablejsapi=1
This enables the JavaScript API handlers in the player, and also tells the player to alert the containing HTML page via a callback when the player is loaded and ready to receive JavaScript calls. When the player is ready, the JavaScript function onYouTubePlayerReady will be called.
You may optionally pass in a playerapiid parameter, which will identify the player when the onYouTubePlayerReady callback is invoked. Whatever value is passed in as playerapiid will be passed back to onYouTubePlayerReady as the first argument.
http://www.youtube.com/v/VIDEO_ID&enablejsapi=1&playerapiid=ytplayer
Alternatively, you may wish to load the chromeless player into your page if you are building your own custom controls using JavaScript:
http://www.youtube.com/apiplayer?enablejsapi=1
Once the chromeless player SWF has been loaded, you can use cueVideoById() or loadVideoById() to load a particular YouTube video.
See the examples below for more detailed information about how to embed a YouTube player SWF into your page.
In order to call the player API methods, you must first get a reference to the player object you wish to control. This can be done by calling getElementById() on the object or embed tag containing the player SWF if using SWFObject to embed the player SWF.
player.playVideo():Voidplayer.pauseVideo():Voidplayer.stopVideo():VoidstopVideo() is called, a video cannot be resumed without reloading the player or loading a new video (chromeless player only). When calling stopVideo(), the player broadcasts an end event (0).player.clearVideo():VoidstopVideo().player.getVideoBytesLoaded():Numberplayer.getVideoBytesTotal():Numberplayer.getVideoStartBytes():Numberplayer.mute():Voidplayer.unMute():Voidplayer.isMuted():Booleanplayer.setVolume(volume):Voidplayer.getVolume():NumbergetVolume() will return the volume even if the player is muted.player.seekTo(seconds, allowSeekAhead):VoidallowSeekAhead determines whether or not the player will make a new request to the server if seconds is beyond the currently loaded video data. Note that seekTo() will look for the closest keyframe before the seconds specified. This means that sometimes the play head may seek to just before the requested time, usually no more than ~2 seconds.player.getPlayerState():Numberplayer.getCurrentTime():Numberplayer.getDuration():NumbergetDuration() will return 0 until the video's metadata is loaded, which normally happens just after the video starts playing.player.addEventListener(event:String, listener):Voidplayer.getVideoUrl():Stringplayer.getVideoEmbedCode():Stringplayer.loadVideoById(videoId:String, startSeconds:Number):VoidstartSeconds (number can be a float) is specified, the video will start from the closest keyframe to the specified time.player.cueVideoById(videoId:String, startSeconds:Number):VoidplayVideo() or seekTo() is called. startSeconds accepts a float/integer and specifies the time from which the video should start playing when playVideo() is called. If you specify startSeconds and then call seekTo(), the startSeconds is value is ignored and the player plays from the time specified in the seekTo() call. When the video is cued and ready to play, the player will broadcast a video cued event (5).player.setSize(width:Number, height:Number):VoidonStateChangeonError100, 101, and 150. The 100 error code is broadcast when the video requested is not found. This occurs when a video has been removed (for any reason), or it has been marked as private. The 101 error code is broadcast when the video requested does not allow playback in the embedded players. The error code 150 is the same as 101, it's just 101 in disguise!onYouTubePlayerReady(playerid)playerapiid is passed into the player via URL arguments, then it will be passed to this function. This function must be implemented in the HTML page containing the YouTube player.We recommend using SWFObject to embed any players that will be accessed using the JavaScript API. This will allow you to detect the end user's Flash Player version (the JavaScript API requires Flash Player 8 or higher), and also will get rid of the 'Click to activate this control' box when using Internet Explorer to view the player.
To enabled the API in the SWF, you must pass in the parameter enablejsapi=1.
See below for an example of using the script to embed a YouTube player with the JavaScript API enabled, and with a playerapiid of ytplayer.
<script type="text/javascript" src="swfobject.js"></script>
<div id="ytapiplayer">
You need Flash player 8+ and JavaScript enabled to view this video.
</div>
<script type="text/javascript">
var params = { allowScriptAccess: "always" };
var atts = { id: "myytplayer" };
swfobject.embedSWF("http://www.youtube.com/v/VIDEO_ID&enablejsapi=1&playerapiid=ytplayer",
"ytapiplayer", "425", "356", "8", null, null, params, atts);
</script>
The allowScriptAccess parameter in the code is needed to allow the player SWF to call functions on the containing HTML page, since the player is hosted on a different domain from the HTML page.
The only attribute we're passing in is the id of the embed object — in this case, myytplayer. This id is what we'll use to get a reference to the player using getElementById().
swfobject.embedSWF will load the player from YouTube and embed it onto your page.
swfobject.embedSWF(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj)
swfUrlStr - This is the URL of the SWF. Note that we have appended the enablejsapi and playerapiid parameters to the normal YouTube SWF URL to enable JavaScript API calls.replaceElemIdStr - This is the HTML DIV id to replace with the embed content. In the example above, it is ytapiplayer.widthStr - Width of the player.
heightStr - Height of the player.
swfVersionStr - The minimum required version for the user to see the content. In this case, version 8 or above is needed. If the user does not have 8 or above, they will see the default line of text in the HTML DIV.
xiSwfUrlStr - (Optional) Specifies the URL of your express install SWF. Not used in this example.
flashVarsObj - (Optional) Specifies your FlashVars in name:value pairs. Not used in this example.
parObj - (Optional) The parameters for the embed object. In this case, we've set allowScriptAccess.
AttObj - (Optional) The attributes for the embed object. In this case, we've set the id to myytplayer.
See the SWFObject documentation for further explanation.
Once the player is ready, it wil call onYouTubePlayerReady.
To get the reference to the player, use getElementById(). Once you have the object, you can start making calls to the API.
function onYouTubePlayerReady(playerId) {
ytplayer = document.getElementById("myytplayer");
}
You can now call functions using the player reference. For example, if you wanted to play the video when a user clicked a link, it would look like this:
function play() {
if (ytplayer) {
ytplayer.playVideo();
}
}
<a href="javascript:void(0);" onclick="play();">Play</a>
Or simply,
<a href="javascript:ytplayer.playVideo()">Play</a>
Subscribe to events by adding an event listener to the player reference. For example, to get notified when the player's state changes, add an event listener for onStateChange and include a callback function.
function onYouTubePlayerReady(playerId) {
ytplayer = document.getElementById("myytplayer");
ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}
function onytplayerStateChange(newState) {
alert("Player's new state: " + newState);
}
Look at this simple example, which displays much of the functionality. View the source to see what's going on under the hood.
There is also an example of the chromeless player using the JavaScript API.