What is the correct way to initialize Youtube IFrame player API in the closure script?
Right now I have following part in the soy template:
<iframe id="youtube-player" src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
Closure script contains following part:
var player;
onYouTubeIframeAPIReady = function() {
console.log('api ready');
player = new YT.Player('youtube-player', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
};
function onPlayerReady(event) {
console.log('player ready');
event.target.playVideo();
}
function onPlayerStateChange(event) {
}
First I was struggling on getting YT.Player
constructor to work, but then I added extern from https://raw.githubusercontent.com/google/closure-compiler/master/contrib/externs/google_youtube_iframe.js to the closure compiler and player
object was created successfully.
However I am getting api ready
message in the console but not player ready
which means onPlayerReady
is never called.
When I'm trying to create iframe by passing id of empty div
and adding videoId
parameter to YT.Player
constructor options - youtube iframe is created but not pointing to any video.
Also I tried to add onPlayerReady
function to externs but it did not helped as well.
What could be wrong?
Problem is events
field in the YT.Player
constructor options was renamed by closure compiler.
So the correct way to execute it to avoid renaming is:
onYouTubeIframeAPIReady = function() {
console.log('api ready');
player = new YT.Player(playerId, {
'events': {
'onStateChange': onPlayerStateChange
}
});
console.log(player);
};