I need help with managing YouTube iframe players that are already embedded in my webpage. These video players exist in the HTML already, and I want to use JavaScript to control them.
I’ve looked at the iframe API docs and they show how to create fresh players and control them:
var videoPlayer;
function onYouTubeAPIReady() {
videoPlayer = new YT.Player('targetDiv', {
height: '480',
width: '720',
videoId: 'abc123xyz',
events: {
'onReady': handlePlayerReady,
'onStateChange': handleStateChange
}
});
}
This approach makes a brand new player instance and puts it in a div. After that I can use methods like videoPlayer.playVideo()
and videoPlayer.pauseVideo()
.
My problem is that I want to control iframe players that already exist on my page.
With the old Flash embed system, I could easily do:
videoPlayer = getElementById('myPlayerID');
videoPlayer.playVideo();
This method doesn’t work with iframe embeds though. How do I get control of an existing iframe player so I can use the API methods on it?
YouTube API can work with existing iframes, but you need enablejsapi=1
in the src URL. Most people miss this. If your iframe src is https://www.youtube.com/embed/abc123xyz
, change it to https://www.youtube.com/embed/abc123xyz?enablejsapi=1
. Without this parameter, YT.Player can’t talk to the iframe. Hit this same problem last year when updating an old site. Had the iframe, was targeting it right, but nothing worked until I added that parameter. Once you fix the src URL, Tom42Gamer’s method works great for controlling your player.
Just target your existing iframe directly with the YT.Player constructor instead of making a new one. Pass your iframe’s ID as the first parameter rather than an empty div. If your iframe has an ID like ‘existing-player’, initialize it like this:
var existingPlayer;
function onYouTubeAPIReady() {
existingPlayer = new YT.Player('existing-player', {
events: {
'onReady': handlePlayerReady,
'onStateChange': handleStateChange
}
});
}
This keeps your existing iframe but gives you full API access. Don’t include height, width, or videoId parameters since they’re already set in your iframe. Once you’ve done this, all the normal API methods like playVideo() and pauseVideo() work fine.