<iframe width="560" height="315" src="//www.youtube.com/embed/M7lc1UVf-VE" frameborder="0" allowfullscreen></iframe>
I have a few questions on what happens when I embed a YouTube video using source code like above. The code should generate a YouTube Player object that processes the video the way users like. When I generate a Youtube Player by myself using Youtube Player API(instead of using the embed code), I can call call functions on it.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
//player.playVideo(); will play the video.
My question is, how do I control the player object generated by the embed code? To put it in another way, from page http://www.youtube.com/watch?v=M7lc1UVf-VE, how do I play the video by calling SOMEPlayer.playVideo()
? When you go to the url, ytplayer
object is available, but it doesn't seem to contain the necessary functions.
This question might be a duplicate of this.
A great way to do this without loading the IFrame API in the parent window is to grab the object from the IFrame
Maximus S gave a perfectly correct answer. The official YouTube IFrame Player API docs suggest initialising the player through a unique id of an iframe with the video as
var yPlayer = new YT.Player('unique-id');
.For the future readers of this question looking for a way to generate a YouTube Player from a reference to an iframe element without id (as myself), it is possible to do so by running
var yPlayer = new YT.Player(iframeElement);
if you addtype="text/html"
attribute to the iframe element and setenablejsapi=1
parameter in thesrc
attribute:<iframe type="text/html" height="360" width="640" src="https://www.youtube.com/embed/jNQXAC9IVRw?enablejsapi=1"></iframe>
Full snippet
This can be done like the following.
Given a general YouTube embed source code:
<iframe width="560" height="315" src="//www.youtube.com/embed/M7lc1UVf-VE" frameborder="0" allowfullscreen></iframe>
a. Add a
enablejsapi
parameter and set it trueindex.html
<iframe width="560" height="315" src="//www.youtube.com/embed/M7lc1UVf-VE" frameborder="0" enablejsapi="1" allowfullscreen></iframe>
b. Give it a unique id
<iframe id="youtube-video" width="560" height="315" src="//www.youtube.com/embed/M7lc1UVf-VE" frameborder="0" enablejsapi="1" allowfullscreen></iframe>
c. Load iFrame API and create a player that references the existing iFrame
application.js
The best answer is almost right. You have to place "enablejsapi=1" on the iframe src. Something like: