Blog

In case you haven’t noticed, Google Tag Manager is getting an upgrade which will soon be automatically pushed by Google to all existing GTM V1 accounts starting June 1, 2015. Voluntary migration to this new version, V2, is also already in play. If you haven’t had a chance to familiarize yourself with the new version, then read more about it here.

Some of the changes include:

  1. “rules” are now renamed to “triggers”
  2. “macros” are now renamed to “variables”
  3. auto-event listeners are no longer needed, and firing a tag based on a click is done by creating a trigger type of “Click”
  4. built-in variables will replace the standard, built-in macros (eg. {{url}}, {{element id}}, {{event}}, etc.)

and there are many more!

This blog post is an update to our YouTube video tracking post, originally authored by Stéphane Hamel. We have highlighted the changes to Stéphane’s original GTM implementation to capture the changes needed to migrate your YouTube tracking from V1 to V2. The same prerequisites from the original V1 implementation apply to V2, and the only differences are in the configuration of the tags, triggers, and variables. We’ve also restructured the steps in Stephane’s original instructions to make it even more streamlined. So here we go!


Create Your Variables

Web Property ID

This variable holds the value of the GA web property ID to which data will be sent.

  • Variable name:
    • WebProperty ID
  • Variable type:
    • Constant
  • Variable configuration:
    • Value = UA-XXXXXX-Y (use your own web property ID)

Variable Configuration in GTM

Is YouTube Present?

This variable, when executed, checks the content of the page for any embedded YouTube. If found, “true” is returned, otherwise “false” is returned.

  • Variable name:
    • YouTube is present
  • Variable type:
    • Custom JavaScript
  • Variable configuration:
// Return "true" if there is at least one YouTube video on the page
function () {
   for (var e = document.getElementsByTagName('iframe'), x = e.length; x--;)
   if (/youtube.com\/embed/.test(e[x].src)){
      return true;
   }
   return false;
}Checks the content of the page for any embedded YouTube.

Data Layer Category

Define a macro that will hold the value of the event category name pushed from the data layer.

  • Variable name:
    • dataLayer category
  • Variable type:
    • Data Layer Variable
  • Variable configuration:
    • Data Layer Variable Name: eventCategory
    • Data Layer Version: Version 2

Defines a macro that will hold the value of the event category name pushed from the data layer.

Data Layer Action

Define a macro that will hold the value of the event action name pushed from the data layer.

  • Variable name:
    • dataLayer action
  • Variable type:
    • Data Layer Variable
  • Variable configuration:
    • Data Layer Variable Name: eventAction
    • Data Layer Version: Version 2

Defines a macro that will hold the value of the event action name pushed from the data layer.

Data Layer Label

Define a macro that will hold the value of the event label name pushed from the data layer.

  • Variable name:
    • dataLayer label
  • Variable type:
    • Data Layer Variable
  • Variable configuration:
    • Data Layer Variable Name: eventLabel
    • Data Layer Version: Version 2

Defines a macro that will hold the value of the event label name pushed from the data layer.

Create Your Triggers

YouTube Event Trigger

Define a trigger that is executed when the dataLayer event name is “youtube”.

  • Trigger name:
    • YouTube event
  • Trigger event type:
    • Custom Event
  • Trigger fires on:
    • Event name: youtube

Defines a trigger that is executed when the dataLayer event name is "youtube"

YouTube Present Trigger

Define a trigger that is executed when the value returned from the variable “YouTube is present” is true, and when the event is “gtm.dom”.

  • Trigger name:
    • YouTube present
  • Trigger event type:
    • Custom Event
  • Trigger fires on:
    • Event name: gtm.dom
    • “YouTube is present” equals true

Defines a trigger that is executed when the value returned from the variable "YouTube is present" is true, and when the event is "gtm.dom"

Create Your Tags

YouTube Event Tag

This tag sends in the event data, that is pushed from the dataLayer, to the GA property.

  • Tag name:
    • YouTube Event
  • Tag product:
    • Google Analytics
  • Tag type:
    • Universal Analytics
  • Tag configuration:
    • Tag type: Universal Analytics
    • Tracking ID: {{WebProperty ID}}
    • Track Type: Event
    • Category: {{dataLayer category}}
    • Action: {{dataLayer action}}
    • Label: {{dataLayer label}}
    • Fields to Set: Field Name = “useBeacon”, Field Value = “true”
  • Tag firing rule:
    • Tag triggered by “YouTube event” trigger

This tag sends in the event data, that is pushed from the dataLayer, to the GA property.

YouTube Listener Tag

This tag detects if there are any embedded YouTube videos on the page. If there are, then it listens for various actions coming from interactions with those videos, or when the video progresses.

  • Tag name:
    • YouTube Listener
  • Tag product:
    • Custom HTML Tag
  • Tag configuration:
    • Tag type: Custom HTML
    • HTML: (click here for a copy of the YouTube listener code)
  • Tag firing rule:
    • Tag triggered by “YouTube present” trigger

YouTube Listener

 

Here is the code for you to copy/paste:

 


Don’t forget to thoroughly test your implementation in Preview mode before you go live with it.

Good luck with your YouTube video tracking! If you have any suggestions to improve this tracking, please don’t hesitate to let us know: nyuen@cardinalpath.com

Related Resources

New to Tag Management Systems (TMS)?  This article explains Why Tag Management is the Way Forward in 2016, our State of Digital Marketing Analytics in the Top 500 Online Retailers report summarizes the adoption rate of TMS in eCommerce, and our expert panel had a lively discussion about the insights uncovered by the report.

Is the data layer the be all and end all of tag management? In this article, we explore the benefits and caveats of using a data layer versus DOM-scraping techniques.

(more…)

Anyone looking to expand the depth of their web analytic collection using Google Tag Manager has more than likely come across detailed technical implementation documents singing praise and touting that anyone who’s anyone is leveraging this awesome functionality.  I myself have sung its praises in my CPTA speaking engagement adventures and to clients.  The general vibe I get is that people know they should be using it, but no one seems to know how, or more importantly why.

What is it – an analogy

First and foremost, let’s start with an analogy to explain what exactly a data layer is.  I want you to imagine you’re in charge of a restaurant, which is your website.  Like any other restaurant you have customers, or visitors, that come in and order food off the menu.  Each plate of food represents a page on your website.  Each plate of food is made up of a few things like mashed potatoes, corn, or meatloaf just like a page on your website has buttons, polls, links, and content.  Serving up those plates of food is your wait staff who runs into the back to grab everything and serve it up to the customers just like server side code on a website does with a database. Now in this restaurant you frequently have customers coming in, asking for the same food as the other patrons, and leaving.  To expedite this you create a buffet, or data layer.  Whenever the wait staff runs into the back to get a plate for a customer you tell them to also grab a plate for the buffet.  Someone orders mashed potatoes the waiter will give some to the customer, and then put some out in the buffet.  The datalayer is simply making data available for another application to take as needed.

Why it’s cool

If you were to use a datalayer outside of GTM, you would have to manually build out that functionality to your site.  Some other web applications have this functionality so it’s case by case.  GTM is natively stocked with the ability to push items to the data layer.  If you’re using a GTM container on your site then you can leverage the datalayer code.  This pre-packaged functionality saves development a lot of time and effort on creating.  A single line of code can push important values to the data layer.  This code can be executed on your site, or you can even use a custom HTML GTM tag to push things into the data layer.  It’s super cool because its significantly easier than it has been in the past.  Less effort with bigger results.

Why you should care

Usage of the data layer will greatly customize the reports you see in whatever reporting platform you’re sending data to in GTM.  Anything and everything served up on a page can be served up to the data layer.  Let’s say for example you’re sending data to a Universal Analytics account.  UA has the ability to create custom dimensions and populate those with custom metrics.  You could use the data layer to push what type of member someone is to these dimensions after they log in or you could push the category of a blog page.  The datalayer is also leveraged to inform GTM when something happens.  This is a critical part for event management.  Think back to the buffet analogy.  Every time a server puts steak in the buffet, everyone who loves steak comes to your buffet and grabs some. I hope this gives some clarity to what the data layer is and how it fits into the process of GTM.  Granted this is a simplified view, there really is a lot of depth to this feature I have not covered.  Conceptually try to think of the data layer as a big buffet for GTM or other third party web applications.  Ask yourself, what information on this page do I want to see in my reports?  That’s the data you push into the data layer.

February 11th, 2015 update
November 15th, 2014 update
  • track onunload event
  • minor fix to error reporting
June 20th, 2014 update
  • now supports multiple players on the same page
  • includes optional code to add the necessary enablejsapi=1 to the video URL
  • now track the video title instead of the video id
September 16th, 2015 update

During our GTM+UA webinar I was asked about tracking YouTube videos with the help of Google Tag Manager and Universal Analytics. I quickly demonstrated how we’re doing it in our WASP playground.

Here’s a step by step guide to the macros, tags and rules required to track YouTube video embeds on your website.

A note for Google Analytics users: For sake of demonstration I’m showing Universal Analytics, but you could easily replace the Universal Analytics Event by a regular Google Analytics one and everything will work fine.

Prerequisites

We will use the YouTube JavaScript API to expose user interactions with the video. In order for this to work, each of your YouTube embeds will need to include “enablejsapi=1” to the link of the video, for example:

<iframe width="420" height="315" src="//www.youtube.com/embed/Rvw0uxuYBCo?enablejsapi=1" frameborder="0" allowfullscreen></iframe>

Note: the “Is Youtube present” macro could be modified to automatically add the enablejsapi if it’s not there, but this will result in a quick flash of the Youtube frame.

Note: by default, related videos will be shown and tracked. If you want to disable this, add “&rel=0” to the Youtube embed link.

What you’ll get

Under Behavior/Events/Top Events, you will see an event category named “video”, with event actions named “pause”, “play”, 0%, 25%, 50%, 75% and 100%. The event label will be the unique identifier of the video.

Custom Report for Video Performance

If you want to get details about how individual videos are performing, follow those steps:

  1. Go in yout Behavior/Events/Top Events/video report;
  2. Click on “Customize” in the top left of the report;
  3. Under Dimension Drilldown, remove the “Event Category” dimension and switch “Event Action” with “Event Label”, so it now reads Event Label/Event Action;
  4. Modify the filter so it now reads “Event Category equals video”, so only videos are shown in this new custom report;
  5. Voilà! You now have detailed performance info about each individual video embedded on your website.

Macros

Is Youtube present?

You have two options here, either use this macro to automatically detect when a video is embedded on a page, or use a rule to include the Youtube Listener tag only on pages where you know there’s a video.

Macro Name: Youtube is present
Macro Type: Custom JavaScript
Custom JavaScript:
// Return "true" if there is at least one Youtube video on the page
function () {
    for (var e = document.getElementsByTagName('iframe'), x = e.length; x--;)
        if (/youtube.com\/embed/.test(e[x].src)) return true;
    return false;
}

event

Macro Name: event
Macro Type: Custom Event

dataLayer action

Macro Name: dataLayer action
Macro Type: Data Layer Variable
Data Layer Variable Name: action

dataLayer label

Macro Name: dataLayer label
Macro Type: Data Layer Variable
Data Layer Variable Name: label

Tags

Listen for Youtube activity

Tag Name: Youtube Listener
Tag Type: Custom HTML Tag
Firing Rule: Youtube present
HTML:
<script type="text/javascript">
// OPTIONAL: Enable JSAPI if it's not already on the URL
// note: this will cause the Youtube player to "flash" on the page when reloading to enable the JS API
for (var e = document.getElementsByTagName("iframe"), x = e.length; x--;)
  if (/youtube.com\/embed/.test(e[x].src))
     if(e[x].src.indexOf('enablejsapi=') === -1)
        e[x].src += (e[x].src.indexOf('?') ===-1 ? '?':'&') + 'enablejsapi=1';

var gtmYTListeners = []; // support multiple players on the same page
// attach our YT listener once the API is loaded
function onYouTubeIframeAPIReady() {
    for (var e = document.getElementsByTagName("iframe"), x = e.length; x--;) {
        if (/youtube.com\/embed/.test(e[x].src)) {
            gtmYTListeners.push(new YT.Player(e[x], {
                events: {
                    onStateChange: onPlayerStateChange,
                    onError: onPlayerError
                }
            }));
            YT.gtmLastAction = "p";
        }
    }
}

// listen for play/pause, other states such as rewind and end could also be added
// also report % played every second
function onPlayerStateChange(e) {
    e["data"] == YT.PlayerState.PLAYING && setTimeout(onPlayerPercent, 1000, e["target"]);
    var video_data = e.target["getVideoData"](),
        label = video_data.video_id+':'+video_data.title;
    if (e["data"] == YT.PlayerState.PLAYING && YT.gtmLastAction == "p") {
        dataLayer.push({
            event: "youtube",
            action: "play",
            label: label
        });
        YT.gtmLastAction = "";
    }
    if (e["data"] == YT.PlayerState.PAUSED) {
        dataLayer.push({
            event: "youtube",
            action: "pause",
            label: label
        });
        YT.gtmLastAction = "p";
    }
}

// catch all to report errors through the GTM data layer
// once the error is exposed to GTM, it can be tracked in UA as an event!
// refer to https://developers.google.com/youtube/js_api_reference#Events onError
function onPlayerError(e) {
    dataLayer.push({
        event: "error",
        action: "GTM",
        label: "youtube:" + e
    })
}

// report the % played if it matches 0%, 25%, 50%, 75% or completed
function onPlayerPercent(e) {
    if (e["getPlayerState"]() == YT.PlayerState.PLAYING) {
        var t = e["getDuration"]() - e["getCurrentTime"]() <= 1.5 ? 1 : (Math.floor(e["getCurrentTime"]() / e["getDuration"]() * 4) / 4).toFixed(2);         if (!e["lastP"] || t > e["lastP"]) {
            var video_data = e["getVideoData"](),
                label = video_data.video_id+':'+video_data.title;
            e["lastP"] = t;
            dataLayer.push({
                event: "youtube",
                action: t * 100 + "%",
                label: label
            })
        }
        e["lastP"] != 1 && setTimeout(onPlayerPercent, 1000, e);
    }
}


// Crossbrowser onbeforeunload hack/proxy
// https://developer.mozilla.org/en-US/docs/WindowEventHandlers.onbeforeunload
window.onbeforeunload = function (e) {
 var e = e || window.event;
 // For IE and Firefox prior to version 4
 if(e)
 e.returnValue = 'na';
 // For Safari
 return 'na';
};
window.onbeforeunload = trackYTUnload;
 
function trackYTUnload() {
 for (var i = 0; i < gtmYTplayers.length; i++)
 if (gtmYTlisteners[i].getPlayerState() === 1) { // playing
 var video_data = gtmYTlisteners[i]['getVideoData'](),
 label = video_data.video_id+':'+video_data.title;
 dataLayer.push({
 event: 'youtube',
 action: 'exit',
 label: label
 });
 }
}
// load the Youtube JS api and get going
var j = document.createElement("script"),
    f = document.getElementsByTagName("script")[0];
j.src = "//www.youtube.com/iframe_api";
j.async = true;
f.parentNode.insertBefore(j, f);
</script>

UA Youtube event

If you are using Google Analytics instead of Universal Analytics, simply change the Tag Type to Google Analytics and everything will work fine.

Tag Name: Youtube Event
Tag Type: Universal Analytics
Tracking ID: UA-XXXXXX-Y
Track Type: Event
Event Tracking Parameters:
Category: {{event}}
Action: {{dataLayer action}}
Label: {{dataLayer label}}
Firing rule: Youtube event

Rules

Youtube embed found on a page

Rule Name: Youtube present
Conditions: {{event}} equals gtm.dom AND {{youtube is present}} equals true

Youtube is telling us something

Rule Name: Youtube event
Conditions: {{event}} equals youtube

Putting it all together

That’s it! Now you can track Youtube video embeds on your own website thanks to Google Tag Manager and Universal Analytics.

Don’t forget to use Google Tag Manager “debug & preview” with WASP to make sure everything works fine before you publish.

This topic, and many more, are covered in our GTM+UA  Master Class. Please check the Cardinal Path training calendar for more locations.

Check out the new, and up to date version by Nicky Yuen.

Cardinal Path’s Stephane Hamel will present a session on how to use Google Tag Manager (GTM) to upgrade to Universal Analytics (UA) on February 6th, 2014.

The webinar will be a practical demonstration coupled with best practices in using GTM for UA and some information about tags, rules and macros.

Hamel has also put out a survey to his over 2000-member Google+ circle asking about UA migration and whether or not people are intending to use GTM. Survey results will be presented at the start of the webinar.

View the on-demand webinar here

Google Tag Manager

YouTube Video Tracking with Google Tag Manager (V2) and Universal Analytics: A Step-by-Step Guide

This tag sends in the event data, that is pushed from the dataLayer, to the GA property.

In case you haven’t noticed, Google Tag Manager is getting an upgrade which will soon be automatically pushed by Google to all existing GTM V1 accounts starting June 1, 2015. Voluntary migration to this new version, V2, is also already in play. If you haven’t had a chance to familiarize yourself with the new version, … Read Full Post

Tag Management: data layer/DOM-scraping pros & cons

Is the data layer the be all and end all of tag management? In this article, we explore the benefits and caveats of using a data layer versus DOM-scraping techniques.

The Google Tag Manager DataLayer Explained

Cardinal Path blog post

Anyone looking to expand the depth of their web analytic collection using Google Tag Manager has more than likely come across detailed technical implementation documents singing praise and touting that anyone who’s anyone is leveraging this awesome functionality.  I myself have sung its praises in my CPTA speaking engagement adventures and to clients.  The general … Read Full Post

YouTube video tracking with GTM and UA: a step by step guide

February 11th, 2015 update Save time! import/merge the required configuration for the new GTM UI! improved in-line documentation and minor bug fixes November 15th, 2014 update track onunload event minor fix to error reporting June 20th, 2014 update now supports multiple players on the same page includes optional code to add the necessary enablejsapi=1 to the … Read Full Post

Webinar on Using Google Tag Manager to migrate to Universal Analytics Announced

Cardinal Path blog post

Cardinal Path’s Stephane Hamel will present a session on how to use Google Tag Manager (GTM) to upgrade to Universal Analytics (UA) on February 6th, 2014. The webinar will be a practical demonstration coupled with best practices in using GTM for UA and some information about tags, rules and macros. Hamel has also put out … Read Full Post

Benchmark Your Marketing Analytics Maturity

See how your marketing analytics performs against thousands of organizations. (Approx. 5 minutes).