YouTube Tracking In Google Analytics & Google Tag Manager

By /

May 11, 2015

blog-youtube-google-analytics

My colleague Sayf Sharif has long been an advocate of tracking YouTube videos with Google Analytics. Our LunaMetrics YouTube tracking script has been copied, cloned, forked, and borrowed more than a few times. It’s time to bring our script up to date with the latest changes in Google Analytics and Google Tag Manager.

Also, Google recently finished the process of deprecating version two of their data API, which our script has depended on for fetching video titles. If you are using an old version of the script, you’ll see all of your videos titles set to https://youtube.com/devicesupport as of a few days ago.

After a little tinkering, we’ve updated the GitHub repo with version 7 of the illustrious LunaMetrics YouTube Google Analytics tracking code. Let’s take a look at what’s inside.

What’s New

This latest version is a plug-and-play tracking solution for tracking user interaction with YouTube videos in Google Analytics. It will detect if Google Tag Manager, Google Analytics (Universal), or Google Analytics (Classic) is installed on the page, in that order, and fire events when users interact with the video.

It includes support for delivering hits directly to Universal or Classic Google Analytics, or for pushing Data Layer events to be used by Google Tag Manager. You can find the code on our GitHub repo.

Installation

Note: This plugin relies on the window.onYouTubeIframeAPIReady namespace and will throw an error if it is currently in use by another script. Check the console for an error if it appears to not be working, and ensure you aren’t already trying to track YouTube videos with other code.

Universal or Classic Google Analytics Installation:

The plugin is designed to be plug-and-play. By default, the plugin will try and detect if you have Google Tag Manager, Universal Analytics, or Classic Google Analytics, and use the appropriate syntax for the event. If you are not using Google Tag Manager to fire your Google Analytics code, store the plugin on your server and include the lunametrics-youtube-v7.gtm.js script file somewhere on the page.

Google Tag Manager Installation

Create a new Custom HTML tag and paste in the below:

In the space between the <script> and </script> tags, paste in the contents of the lunametrics-youtube-v7.gtm.js script, found here.

Configuration

Universal or Classic Google Analytics Configuration

Once everything installed on your own site, this script will fire a Google Analytics event with the following settings:

  1. Event Category: Videos
  2. Event Action: (Action, e.g. Play, Pause)
  3. Event Label: (URL of the video)

Configuring Which Events Fire

If you are not using Google Tag Manager to fire your Google Analytics code, you might want to configure the script to fire or not fire certain events. By default, it will fire:

  • Play events
  • Pause events
  • Watch to End events

To change which events are fired, edit the configuration at the end of the script. For example, if you’d like to fire Buffering events and not fire Pause events:

The available events are Play, Pause, Watch to End, Buffering, Unstarted, and Cueing. An example configuration object is at the bottom of the script file.

Forcing Universal or Classic Analytics

By default, the plugin will try and fire Data Layer events, then fallback to Univeral Analytics events, then fallback to Classic Analytics events. If you want to force the script to use a particular syntax for your events, you can set the ‘forceSyntax’ property of the configuration object to an integer:

Setting this value to one of the following numbers:

  • 0 will force the script to use Google Tag Manager events
  • 1 will force it to use Universal Google Analytics events
  • 2 will force it to use Classic Google Analytics events

Google Tag Manager Configuration

Once you’ve added the script to your container (see Google Tag Manager Installation), Data Layer events will occur for all of the following:

  • Play
  • Pause
  • Watch to End
  • Cueing
  • Buffering
  • Unstarted

Create the following Variables:

  • Variable Name: videoUrl
    • Variable Type: Data Layer Variable
    • Data Layer Variable Name: attributes.videoUrl
    • This is the URL of the video on YouTube
  • Variable Name: videoAction
    • Variable Type: Data Layer Variable
    • Data Layer Variable Name: attributes.videoAction
    • This will be the action the user has taken, e.g. Play, Pause, or Watch to End

video-variables

Create the following Trigger:

  • Trigger Name: YouTube Video Event
    • Trigger Type: Custom Event
    • Event Name: youTubeTrack
    • Add Filters:
      • videoAction MATCHES REGEX Play|Pause|Watched To End
        enter a pipe (‘|’) separated list of the actions you want to track

youtube-event-trigger

Create your Google Analytics Event tag

  • Tag Type: Google Analytics
    • Choose a Tag Type: Universal Analytics (or Classic Analytics, if you are still using that)
    • Tracking ID: <Enter in your Google Analytics tracking ID>
    • Track Type: Event
    • Category: Videos
    • Action: {{videoAction}}
    • Label: {{videoUrl}}
    • Fire On: More
      • Choose from existing Triggers: YouTube Video Event

youtube-GA-Event

Configuring Which Events Fire

You can reconfigure the YouTube Video Event trigger anytime you’d like to track more of the events included, such as Cueing or Buffering. Remember that GTM events are not Google Analytics Events, and whether a GTM event sends data to Google Analytics is entirely up to how your Triggers are configured.

Getting Video Titles

Because of the deprecated YouTube API, this script no longer provides the titles of the videos. We chose to go with the most consistent method, which means that instead of the human-readable titles you would have gotten as your Event Label before, you’ll now see the URL of the video itself, e.g. https://www.youtube.com/watch?v=dQw4w9WgXcQ.

Once you have the video URL, you can use something like Excel or Google Spreadsheets to help convert those into readable titles. Another option would be to use a Google Tag Manager Lookup Table to translate the URLs into titles before sending the information to Google Analytics. We have a spreadsheet to help convert URLs to Titles, as well as blog about quickly creating lookup tables.

Coming Soon

We have plans to add percentage completion tracking at some point in the near future. Do you have another feature request for the plugin? Drop us a line in the comments, or better still, submit a pull request and we’ll see if we can get it in.

Dan Wilkerson is an Analytics Engineer at LunaMetrics. He is passionate about web technology, measurement, and analysis. Dan is the winner of the 1999 Forge Road Elementary School Science Fair for his groundbreaking report on how magnets work. (ICP, take note.) Dan has worked at LunaMetrics in social media, as our marketing manager, and now in our analytics department.

  • Frédéric Gaye

    Hi Dan,
    Very nice solution but it seem have a “little” bug with GTM. We have a “flash” on youtube video (when page loading video disappears briefly then reappears). Except this point all is fine.
    PS : Yes, add percentage completion tracking will be a nice idea.

    • Dan Wilkerson

      Hi Frédéric,

      This is expected behavior – if your video embed doesn’t have the proper parameters (?enablejsapi=1&origin=www.hostname.com) or is an older style object, the tracking won’t work. The script detects these issues and reloads the video. If you don’t want that to happen, you can add those parameters to the src attribute of the video you’ve embedded.

      Dan

  • Katya De Palma

    HI Dan, thanks for ur guidelines. Just a info: you suppose to do it with Version 2, but I can manage the same with the version 1 of gtm?
    I mean I fixed all the event /tag /macro in V1 but doesn’t work.
    many thanks for ur help.
    k.

    • Dan Wilkerson

      Hi Katya,

      Sure can, but they’re migrating everyone to v2 on June 1st.

      Dan

  • Sarah Peduzzi

    What voodoo magic is this? Much learning. So excite.

    • Dan Wilkerson

    • Dan Wilkerson

      Aw yiss.

  • Amanda Dominy

    I don’t seem to be able to get this to work at all. I have a WordPress site, with a Bootstrap theme that already uses JQuery. I have enqueued the script lunametrics-youtube-v7.gtm.js in the header, after jquery. I’m using Universal Analytics, and I’m happy with the events you have by default, so I have not configured anything else. I’m using the standard iframe embed code (eg: ). Here is a link with an example video on our site: http://www.encounters.co.za/siren-of-faso-fani/

    I don’t know what else is going wrong?

    (PS: I added a space to the iframe code because I couldn’t figure out how to [pre] code here…

    • Dan Wilkerson

      Hi Amanda,

      The newest version removes the jQuery dependency.

      When I look at the video on the page, it’s being served via player.cxtn.net, not a standard YouTube Iframe. Are you using a plugin of some kind to deliver this video? That’s why it’s not working, as far as I can tell.

      Dan

      • Amanda Dominy

        Hi there, yes, I installed a plugin from vidanalytic.com in the mean time to track the views. I will disable it now for a couple of days – would you mind taking another look?

        • Dan Wilkerson

          Hi Amanda,

          You’ve got another file loaded in after the YouTube tracking script that is overwriting the window.onYouTubeIframeAPIReady endpoint with it’s own function. This happens before the Iframe API is loaded in and can call the LunaMetrics script, so you don’t see an error or anything it’s simply lost. If you want to have both scripts, you’ll need to add logic to them both to detect if there is already a function registered at that endpoint and to concatenate their execution, Check this file for more. http://www.encounters.co.za/wp-content/plugins/slideshow-jquery-image-gallery/js/min/all.frontend.min.js?ver=2.2.23

          Dan

          • Amanda Dominy

            Ah! Thanks so much – I’ll see if I can do without the slideshow plugin, or better yet, do it natively in Bootstrap.

          • Amanda Dominy

            Ok, I’ve removed that plugin (replacing my slideshow with a native bootstrap carousel). I can see now that the enablejsapi bit is properly added to my videos, and it’s being served from youtube, but I’m still not seeing any events triggering in my analytics account (looking at the Real Time events, last 30 min). Could it be a caching problem? Thanks so much for the help and feedback, in advance.

  • Tiaan Van Zyl

    Hi Dan,

    I have a noob question – should the custom HTML tag fire on all page of the website?

    Oh yes, this is pretty cool!

    Thanks
    Tiaan

    • Dan Wilkerson

      Hey Tiaan,

      It can, but you’re adding extra code execution that you don’t really need. You might instead create a custom JS variable that checks for any YouTube videos on the page and returns ‘true’ if it sees one, then use that as a firing Trigger.

      Dan

      • Tiaan Van Zyl

        Hey Dan,

        Thanks for the feedback. I actually did a quick search within Google and found the following javascript code to detect if there is a youtube video present. I will create a trigger when this code snippet fires, then the trigger should fire on any pageview (type) of the custom html tag? –

        function () {

        for (var e = document.getElementsByTagName(‘iframe’), x = e.length; x–;)

        if (/youtube.com/embed/.test(e[x].src)) return true;

        return false;

        }

        Thanks,
        Tiaan

  • http://escapestudio.hr Zorin Radovancevic

    Hi Dan,

    tested the script and it works nicely – thanks!

    One question though with UA simple implementation GA debug reported ‘Unrecognized Positional Argument: false’. I have changed your js and instead of false used {nonInteraction: 1|0} and no more warnings were present.

    Kind regards,
    Zorin

    • Dan Wilkerson

      Hi Zorin,

      Good catch! Pushed a fix to the repo. Much appreciated.

      Dan

  • Lucas

    Hi Dan, great video! It was exactly what I needed to start tracking videos on the company site. I was researching on Google Tag Manager and it stated that we can also add the GA tracking code to our Tag Manager container. In this case, can I remove the older GA script?

Contact Us.

LunaMetrics

24 S. 18th Street, Suite 100,
Pittsburgh, PA 15203

Follow Us

1.877.220.LUNA

1.412.381.5500

getinfo@lunametrics.com

Questions?
We'll get back to you
in ONE business day.