Ever wonder how many of users watched an embedded YouTube video all the way through? How about how many simply pause the video halfway through out of boredom? This is all possible thanks to YouTube's Javascript API (JSAPI).
The Setup
First and foremost in order to do JavaScript callbacks from the video a few parameters need to be added to the embed code. Specifically enablejsapi=1. Also there's another parameter which will need to match the ID of the OBJECT element playerapiid=video1.
<object data="http://www.youtube.com/v/L4H8vvGVoS0&enablejsapi=1&playerapiid=L4H8vvGVoS0" id="L4H8vvGVoS0" type="application/x-shockwave-flash" height="344" width="425">
<param value="http://www.youtube.com/v/L4H8vvGVoS0&enablejsapi=1&playerapiid=L4H8vvGVoS0" name="movie"></param>
<param value="always" name="allowscriptaccess"></param>
</object>
One thing to note: In order to get Internet Explorer to play nice, the default YouTube embed code didn't work for me. I needed to modify it to the above to successfully track my video in ALL browsers. I suspect this is related to Non-IE browsers using the EMBED element and IE using OBJECT. My above example uses OBJECT without any extra elements needed. For more on this see my article titled Embedding Flash Without Click To Activate Using Valid HTML
Pseudo Code
Since the Javascript required to accomplish this is about 60 lines long, I'll only explain a top level view of the code. When an action occurs on the YouTube video it will call the onYouTubePlayerReady function along with the ID of the OBJECT element. The details of each video are then stored in an anonymous function (correct me if I've got the wrong terminology on this) using youTubePlayerLoggers[id].
//Global variables
//Function that is called automatically by the embedding videos
function onYouTubePlayerReady(id)
{
//Define video level variables
//Setup video state constants
//Store information specific to each video
youTubePlayerLoggers[id] = function(state)
{
//Check video state, log action
};
//Bind events to video
}
Viewing The Data In Google Analytics
Below are the reports that will be generated in Google Analytics. The data can be accessed in the Event Tracking report which is found under the Content category.