Customers often ask us how they can track user interaction with embedded YouTube videos on their site. This requires the development team to add Javascript to your site that fires Google Analytics events to capture interactions like Play, Pause, or Finish. This blog describes how it is done using the YouTube Player API.

Getting Started - Decide what you want to track

The first thing you need to decide is what you want to know about your videos. Typically, you want to know if people are playing them. Visitors may be coming to a page containing a video, but not playing it. Maybe they get distracted by other content on the page, or the video image doesn't look interesting and they move on. So, a key measure of engagement is the percentage of pageviews where the visitor actually plays the video. We call this the Play Percentage.

Secondly, you probably want to track how often visitors watch the video through until the end. A visitor might click play, but find that they aren't interested in the video after a few seconds and then move on. Therefore, another key measure of engagement is the percentage of players who finish the video. We call this the Finish Percentage.

You can also track pauses, and a few other events. In this blog post, we will focus on the key engagement metrics of Play Percentage and Finish Percentage.

How Embedded Videos are Tracked

Commonly, YouTube videos are placed on a site using an iframe embedding. Here is the code used on this blog post to embed the test video below.

[code language="javascript" light="true"]

<iframe id="youTubePlayer" width="420" height="315" src="http://www.youtube.com/embed/l0jCR5t13vA?enablejsapi=1&origin=https://megalytic.com" frameborder="0" allowfullscreen></iframe>

[/code]

The trouble with iframes is that you don't have a lot of control over the code that runs inside the frame. You cannot edit the code and add Google Analytics tracking directly.

To get around this problem, we use the YouTube Player API Reference for iframe Embeds. Using this API, we can capture changes in an embedded video that correspond to user interactions.

It's worth noting that this approach only works for visitors using browsers that support the HTML5 postMessage feature. Luckily, that includes most browsers these days, although IE7 does not support it.

Working with the YouTube API

So, the first step is to include the YouTube API on the pages with videos you want to track. That means adding JavaScript to your site to pull in the API code. There are lots of ways to do this. Since this blog is hosted on WordPress, I used the handy CSS & JavaScript Toolbox plugin that lets me add Javascript to exactly the posts where I want it.

Here's the JavaScript that you need to include. This is similar to how the Google Analytics API is added to your site asynchronously. The code is taken directly from Step 2 in the Getting started section of the YouTube documentation.

[code language="javascript" light="true"]

// This code loads the IFrame Player API code asynchronously

var tag = document.createElement('script');

tag.src = "http://www.youtube.com/iframe_api";

var firstScriptTag = document.getElementsByTagName('script')[0];

firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

[/code]

The next step is to add JavaScript that initializes a YouTube player object tied to the iframe where your video is embedded. Make sure your iframe has an id attribute. Above, you can see that this blog is using id="youTubePlayer". The id is the key that YouTube uses to link the player object with the iframe.

Here is the function that you need to add. The YouTube API will call this function once it is fully loaded.

[code language="javascript" light="true"]

// This code is called by the YouTube API to create the player object

function onYouTubeIframeAPIReady(event) {

player = new YT.Player('youTubePlayer', {

events: {

'onReady': onPlayerReady,

'onStateChange': onPlayerStateChange

}

});

}

[/code]

Lastly, you need to add the callback functions that the YouTube API will call when events happen inside the iframe. As you can see in the code above, we need two callback functions - one for the onReady event, and one for the onStateChange event.

The onReady event happens when the player is ready. Since that is not caused by a user interaction, we aren't going to include any Google Analytics tracking code for it. Typically, this event might be used to start the video (if you wanted it to play as soon as the video was loaded). The onStateChange event fires when the player is started, paused, or the video finishes (plus a few more things described here). These are events we want to track with Google Analytics.

We use Google Analytics Event Tracking to log these events in our Google Analytic account. Here's the code.

[code language="javascript" light="true"]

var pauseFlag = false;

function onPlayerReady(event) {

// do nothing, no tracking needed

}

function onPlayerStateChange(event) {

// track when user clicks to Play

if (event.data == YT.PlayerState.PLAYING) {

_gaq.push(['_trackEvent', 'Videos', 'Play', 'Test Video']);

pauseFlag = true;

}

// track when user clicks to Pause

if (event.data == YT.PlayerState.PAUSED && pauseFlag) {

_gaq.push(['_trackEvent', 'Videos', 'Pause', 'Test Video']);

pauseFlag = false;

}

// track when video ends

if (event.data == YT.PlayerState.ENDED) {

_gaq.push(['_trackEvent', 'Videos', 'Finished', 'Test Video']);

}

}

[/code]

You'll notice in the above code that we use Google Analytics Event Actions named "Play", "Pause", and "Finished". These are the Action dimensions that will show up in our Google Analytics reports to track interaction. You may also notice that we've included a pauseFlag variable. This is used to prevent excessive tracking of Pause events. For example, if the user slides the video player control back and forth to rewind or fast forward, a bunch of spurious Pause events are generated by the YouTube API. We don't want to track these, so we only register a Pause event with Google Analytics after a Play event has been tracked. To implement this, the pauseFlag is set to false, except after a Play event. Another quirk to note is that YouTube fires a Pause event right before the video finishes. So, even if the user doesn't do a Pause, you'll see one Pause event for every Finish event.

In order for all this to work, you need to tweek you iframe code a little bit. You'll notice above that the URL used in the iframe in this blog has a couple of extra parameters: enablejsapi=1 and origin=https://megalytic.com.

The enablejsapi parameter tells the YouTube API that it is OK to fire events for this iframe. Without setting it to 1, the tracking callbacks will never be called. The origin parameter "protects against malicious third-party JavaScript being injected into your page and hijacking control of your YouTube player", as described here.

Seeing the results in Google Analytics

Once you have the JavaScript set up, start interacting with your embedded video and cause some Google Analytics events to be fired. You can use the debugger to verify that events are firing. I particularly like using the Google Analytics Debugger for Chrome for this.

Wait a little while (data should start showing up within 2 hours), and then go to Google Analytics to see the events. The category we are using on this blog page is "Videos", so when I open up Google Analytics and navigate to Behavior >> Events >> Top Events, here is what I see.

Click on the Videos category to drill down. You should then see the three types of events (Actions) that you are tracking.

Calculating the Video Metrics

At the beginning of this post, we talked about wanting to track the Finish Percentage and Play Percentage. Google Analytics does not provide these directly, so you will need to calculate them.

For each of these calculated metrics, what you care about is the Unique Events metric coming from Google Analytics. During a visit, a user may click Play many times - particularly if they are pausing the video. The Total Events metric will show multiple Plays, but the Unique Events metric will only show one. What you care about tracking in the Finish Percentage is the percentage of visitors who played the video, who also finished it. So the formula is:

Finished (Unique Events) /Play (Unique Events)

Likewise, the Play Percentage should be calculated using Unique Pageviews. What you care about knowing is the percentage of visits to the page that resulted in the video being played. To get the Pageviews, navigate to Behavior >> Site Content >> All Pages and filter for the page that includes the video you are tracking. Grab the Unique Pageviews metric. The formula for Play Percentage is:

Play (Unique Events) / Unique Pageviews