YouTube iframe API Without External Script

The YouTube API is fairly straightforward, but requires the inclusion of a separate script tag, which then loads another script tag, all so you can do whatever specific thing you need to do. It always bothers me when you have to include a whole library in order to do anything, and while it’s small and minified, I also like to have control over what I’m doing.

Recently I wanted to listen for the end of a YouTube video and run a function. Here’s how I did it:

  • The Iframe tag you receive from YouTube needs to have enablejsapi=1 appended to the url parameters.
  • The YouTube video will send status messages to the main window once it’s told to.
  • Tell the YouTube video that it needs to start sending messages, via postMessage.
    The problem is that this must be done after the YouTube iframe is listening, which is up to us to determine. Since the YouTube video doesn’t post ANY messages (not even a ready message) until it’s told, we have to keep sending postMessages to the iframe until the video starts sending them back.
var interval,
    youtubeIframe=document.getElementById('youtubeVideo').contentWindow;
 
//keep doing this until we get a response
interval = setInterval(function () {
    youtubeIframe.postMessage(
        '{"event":"listening","id":"apiID"}',
        '*');
}, 250);
 
window.addEventListener('message', function (event) {
    //if the message is from the right location
    if(event.source == youtubeIframe){
        if (interval) {
            interval = clearInterval(interval);
        }
        //get the data
        var json = JSON.parse(event.data);
    }
});

Here’s a working example:
JSFiddle

Leave a Reply

Your email address will not be published. Required fields are marked *