Skip to content

Instantly share code, notes, and snippets.

@TastyToast
Created September 4, 2013 00:32
Show Gist options
  • Save TastyToast/6431385 to your computer and use it in GitHub Desktop.
Save TastyToast/6431385 to your computer and use it in GitHub Desktop.
YouTube JS API Helper
/**
* @author Rob W <[email protected]>
* @website http://stackoverflow.com/a/7513356/938089
* @version 20120724
* @description Executes function on a framed YouTube video (see website link)
* For a full list of possible functions, see:
* https://developers.google.com/youtube/js_api_reference
* @param String frame_id The id of (the div containing) the frame
* @param String func Desired function to call, eg. "playVideo"
* (Function) Function to call when the player is ready.
* @param Array args (optional) List of arguments to pass to function func*/
function callPlayer(frame_id, func, args) {
if (window.jQuery && frame_id instanceof jQuery) frame_id = frame_id.get(0).id;
var iframe = document.getElementById(frame_id);
if (iframe && iframe.tagName.toUpperCase() != 'IFRAME') {
iframe = iframe.getElementsByTagName('iframe')[0];
}
// When the player is not ready yet, add the event to a queue
// Each frame_id is associated with an own queue.
// Each queue has three possible states:
// undefined = uninitialised / array = queue / 0 = ready
if (!callPlayer.queue) callPlayer.queue = {};
var queue = callPlayer.queue[frame_id],
domReady = document.readyState == 'complete';
if (domReady && !iframe) {
// DOM is ready and iframe does not exist. Log a message
window.console && console.log('callPlayer: Frame not found; id=' + frame_id);
if (queue) clearInterval(queue.poller);
} else if (func === 'listening') {
// Sending the "listener" message to the frame, to request status updates
if (iframe && iframe.contentWindow) {
func = '{"event":"listening","id":' + JSON.stringify(''+frame_id) + '}';
iframe.contentWindow.postMessage(func, '*');
}
} else if (!domReady || iframe && (!iframe.contentWindow || queue && !queue.ready)) {
if (!queue) queue = callPlayer.queue[frame_id] = [];
queue.push([func, args]);
if (!('poller' in queue)) {
// keep polling until the document and frame is ready
queue.poller = setInterval(function() {
callPlayer(frame_id, 'listening');
}, 250);
// Add a global "message" event listener, to catch status updates:
messageEvent(1, function runOnceReady(e) {
var tmp = JSON.parse(e.data);
if (tmp && tmp.id == frame_id && tmp.event == 'onReady') {
// YT Player says that they're ready, so mark the player as ready
clearInterval(queue.poller);
queue.ready = true;
messageEvent(0, runOnceReady);
// .. and release the queue:
while (tmp = queue.shift()) {
callPlayer(frame_id, tmp[0], tmp[1]);
}
}
}, false);
}
} else if (iframe && iframe.contentWindow) {
// When a function is supplied, just call it (like "onYouTubePlayerReady")
if (func.call) return func();
// Frame exists, send message
iframe.contentWindow.postMessage(JSON.stringify({
"event": "command",
"func": func,
"args": args || [],
"id": frame_id
}), "*");
}
/* IE8 does not support addEventListener... */
function messageEvent(add, listener) {
var w3 = add ? window.addEventListener : window.removeEventListener;
w3 ?
w3('message', listener, !1)
:
(add ? window.attachEvent : window.detachEvent)('onmessage', listener);
}
}
@digitalhuman
Copy link

function postMessage(frame_id, func, args){

    if (window.jQuery && frame_id instanceof jQuery){ 
            frame_id = frame_id.get(0).id; 
    }

    var iframe = document.getElementById(frame_id);

    if (iframe && iframe.tagName.toUpperCase() != 'IFRAME') {
        iframe = iframe.getElementsByTagName('iframe')[0];
    }

    if(iframe) {
        if(typeof(iframe.contentWindow.postMessage) == "function"){

            // Frame exists, 
            iframe.contentWindow.postMessage(JSON.stringify({
                "event": "command",
                "func": func,
                "args": args || [],
                "id": frame_id
            }), "*");
        }
    }
}

@digitalhuman
Copy link

That is the short version

@jashson
Copy link

jashson commented Sep 11, 2017

Is there any possibility to add Event-Listeners like onStateChanged or get any values back from the YT-iFrame after calling callPlayer? callPlayerworks great for all methods that invoke any kind of action to the YT-Player (playVideo, pauseVideo, mute, ...)

// how to add listeners (example not working)
callPlayer(iFrame, "onStateChanged", function (e) {
  // do something after the state of the YT-Player has changed
})
// how get get a return value via callPlayer if the method which is called normally returns a value?
callPlayer(iFrame, "getPlayerState")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment