Introducing JavaScript Player API for iframe embeds
January 20th, 2011 | Published in Youtube API
If you have been enjoying our embed announced back in July we have some good news for you. Starting today, the embed code is the default way to share videos on YouTube.com. We are also introducing an initial beta version of the embed JavaScript Player API, making it a viable alternative for developers who previously used the API exposed by the ActionScript players. Let’s look at an example of the API usage:
//Load player api asynchronously.
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var done = false;
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'JW5meKfy3fY',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(evt) {
evt.target.playVideo();
}
function onPlayerStateChange(evt) {
if (evt.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
This example will play a video for several seconds and then stop playback. An instance of YT.Player is used to control the player, defined by script loaded from http://www.youtube.com/player_api . For more information about the API usage, as always, please consult our Player API documentation and let us know what you think on our Developer Forum.
Cheers,
-Jarek Wilkiewicz, on behalf of the YouTube Player Team
//Load player api asynchronously.
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var done = false;
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'JW5meKfy3fY',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(evt) {
evt.target.playVideo();
}
function onPlayerStateChange(evt) {
if (evt.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
This example will play a video for several seconds and then stop playback. An instance of YT.Player is used to control the player, defined by script loaded from http://www.youtube.com/player_api . For more information about the API usage, as always, please consult our Player API documentation and let us know what you think on our Developer Forum.
Cheers,
-Jarek Wilkiewicz, on behalf of the YouTube Player Team