I've looked through so many questions and the youtube api stuff but for the life of me can't figure out why the onYouTubeIframeAPIReady is not working.
Here is my iframe:
<iframe id="youtube_vid" width="763" height="430" src="https://www.youtube.com/embed/dlJshzOv2cw?theme=light&showinfo=0&rel=0&enablejsapi=1" frameborder="0" allowfullscreen=""></iframe>
And my script:
function callYTapi() {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
console.log('script loaded');
function onYouTubeIframeAPIReady() {
console.log('IframeAPI = Ready');
var player = new YT.Player('youtube_vid', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PAUSED) {
console.log("Paused");
}
if (event.data == YT.PlayerState.PLAYING) {
console.log("Playing");
}
if (event.data == YT.PlayerState.ENDED) {
end();
}
}
}
I get the console.log for the loaded script but not for Iframe ready or anything else. Any ideas? Thanks
The callback functions must be in the global scope. Just move
onYouTubeIframeAPIReady
and the others outsidecallYTapi
.Just to be clear, the accepted answer above seems to work for me in this way:
Load API (from yt documentation)
specify YouTube's built-in ready function "onYouTubeIframeAPIReady" on window
So
this.onYTready
is my function name and located elsewhere. I can confirm myonYTready
function can console logs/debugger breakpoints in Chrome.(edit) you may want to bind this to your function, example:
or 'this' will be for window instead of a specific view you may be using..
Fortunately for me, after a lot of experimenting with console, I had something concrete. I kind of had the same issue until a day ago and figured out how to do when I was within a singleton scope.
Here is what my code looks like: