Controlling multiple YouTube Players at once

I'm constantly using the YouTube Player API to embed videos on sites with special functionality such as hidden controls, looping or synching to live feeds.

Howver one function always seemed to be elusivein the API. This was the ability to control all of the players on a page, regardless of whether they have been embeded using JavaScript on not.

I made a little helper function which stops all youtube players it can find on the current page:

function players(func, args) {
var iframes = document.getElementsByTagName('iframe');
for (var i=0; i<iframes.length; ++i) {
if (iframes[i]) {
var src = iframes[i].getAttribute('src');
if (src) {
if (src.indexOf('youtube.com/embed') != -1) {
iframes[i].contentWindow.postMessage(JSON.stringify({'event': 'command','func': func,'args': args || []}), "*");
}
}
}
}
}

// example usage
players('stopVideo');
This search for all iframes with youtube embeds. It then posts a message with the value you want:
https://developers.google.com/youtube/js_api_reference#Functions