BLOG

Tracking YouTube Videos using Google Analytics

Published May 16, 2014

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.

Tracking YouTube Interaction with Google Analytics


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.

Tracking Video Events in Google Analytics - Category Level

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

video-actions

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

ALSO IN THIS BLOG

When the client first came to you, you talked up the value of Google Analytics. You emphasized the importance of seeing where your traffic was coming from. You went on and on about how Google Analytics can show traffic sources to pinpoint whether people came from search, social media or a specific site referral, and how valuable this data was. You sold them on it, so much so that your client looked forward to receiving that first report, the magical day when they would finally understand where visitors were coming from.
But then the report came, and it looked like this:

 

 

It showed that 10% of your client’s traffic came from “(direct)/(none)”. What does this label mean? How do you explain Direct traffic to your client? Better yet, how do you explain “none”?
Let’s take a closer look at understanding Direct traffic in Google Analytics and how we can address it with clients.
Remember how your mom told you not to stand too close to the television because it might hurt your eyes?

The same rules can apply to data. If you’re too close, you may miss the patterns and trends that are crucial to understanding your website’s performance. You can’t judge a site’s performance looking at data in the bubble of a single day, you must consider any day’s traffic compared to the days before and after.

Google Analytics makes it fairly easy to analyze trends over long periods of time. But it also allows you to stand right in front of that TV, to look at more granular levels of time, right down to the hour.
There’s a better way to get that close to the data, without burning your retinas. We’ll cover how to analyze traffic effectively in today’s post.
Digital marketers spend a lot of time focused on PPC and SEO campaigns in order to drive desirable traffic to a website. The phrases we’re ranking for and bidding on get meticulous attention, so much so that we often forget about some of the other ways that visitors find us.

We put a tremendous amount of the effort we put into reviewing organic search data and PPC campaign performance in analytics. But how closely do we monitor referral reports?

If that’s not a channel you review regularly, you may be missing out on seeing traffic that is coming directly from links you’ve obtained around the web, local business listings, news mentions, and more. Many times, links are only considered as a means to an end, a metric that Google uses in determining how to rank sites in the SERPs (search engine results pages). But the fact is, many of a site’s links may be directly contributing to its traffic.

In this article, we’ll review how to look at referral reports in Google Analytics, and some of the many ways to use that data to better inform your web marketing decisions.