YouTube

How To Track Embedded YouTube Video Play / Pause Events Using Google Tag Manager & Google Analytics

Recently I have noticed that many companies have published / embedded YouTube videos on their websites but no one is tracking Video engagements on these pages.

Few of my friends recently asked me how they can track YouTube embedded videos using Google Tag Manager. I myself Googled this term several times with several keyword variations but couldn’t find any proper step-by-step guide for beginners. Hence, I have decided to write this article for all of my followers.

Throughout this article, I will be using Google Tag Manager to capture the events & will pass this information to Google Analytics. If you don’t know how to implement Google Tag Manager on your website then please refer to this post How To Implement Google Tag Manager Code In WordPress.

Step 1: First of all, you need to modify your YouTube Video Embed Code & add an extra parameter ?enablejsapi=1 to Enable JavaScript API for your embedded videos so you can catch Video Play Events. You can find out more about the API here YouTube API For iFrame. Below is an example of the default YouTube Embed Code with an extra parameter to enable JavaScript API.

<iframe src="https://www.youtube.com/embed/jUnGdf3G92o?enablejsapi=1" width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen"></iframe>

Step 2: Login to your Google Tag Manager & Click on your Container as shown below

Step 3: Click on the Tags from the left-menu & then Click on New button as shown in below image

Step 4:- Now give a name to your Tag & Click on Custom HTML Tag as shown below

Step 5: We will be using a custom JavaScript code to catch all the Video Play Events & add them into DataLayer so we can catch these Events & pass on to Google Analytics for reporting. The JavaScript code we are using was originally written by the CardinalPath website but I made a few customizations to it.

As a next step, please Copy the JavaScript Code from below & Paste it into your Google Tag Manager Custom HTML & Click on Continue button

<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>

Step 6: From the next option screen, Please Click on All Pages if you have a plan to Embed YouTube Videos across the Website or Select the option Some Pages in case you have YouTube Videos Embedded only on few pages. After selecting the right option as per your need, finally Click on Create Tag button 

Step 7: Now, First of all Preview your Tag to make sure its working properly before you put it live

Step 8: Open your Web Page in 2nd tab of Google Chrome which has a YouTube Embedded Video on it & check if YouTube Video Listener Tag is getting fired properly (Please note that Google Tag Manager Preview doesn’t work in any other browser)

Great!!! As you can see that on Page Load event, YouTube Video Player Event Listener Tag was fired successfully

Step 9: I have clicked on the Video Play button and let it run for a minute before hitting the Pause button to see if our tracking code is working perfectly fine and tracking Video Player Events properly. I can clearly see there were 4 YouTube Events in a Summary view as shown below

Step 10: In order to finish our testing & proceed to pass these Event’s values to Google Analytics, lets quickly check what information we are getting in these YouTube Events captured by our code. I am pasting some quick screenshots below

As you can clearly see that our Tracking Code is tracking all the Events successfully including Video Play, Pause & % Watched. Now let’s create Variables based on these Events & pass this info to Google Analytics for Reporting & Analysis

Step 11: So let’s create 3 new DataLayer variables (event, action & label) in order to store the values of these Events. To create DataLayer variables, Please click on Variables from the left menu & click on New button as shown below

Step 12: Give a Name to your Variable, Select Data Layer Variable & Click on Continue

Step 13: On the next screen, enter the Data Layer Variable name same as you are capturing in your Events. I am quickly pasting all the screenshots below for your ease

Step 14: In order to fire an Analytics code, we need to create a Trigger based on YouTube event. This Trigger will only get fired when there are YouTube video Engagements. Now Click on Triggers from the left-menu and then hit the New button. Give a name to your Trigger and Select Custom Event from the options. In the end, type YouTube in the Event Name field and click on Create Trigger as shown below

Step 15: Finally, Let’s create a Google Analytics Event tag now. Click on Tags from the left menu, click on NewSelect the product Google Analytics from the available options then click on Universal Analytics & enter all the details as shown below & finally click on Continue button

Step 16: From the Fire On options, Click on More & Select your Trigger which you just created and hit the Save button. After this finally, Click on Create Tag button

Step 17: Lets put Google Tag Manager in a Preview Mode to test if these events have been passed to Google Analytics or not before Publishing these changes

Good to see that our Google Analytics Event Tracking Tag was fired successfully each time whenever there was a YouTube Video Engagement. Let’s check if these values are available in Google Analytics by logging in your Google Analytics account and by Clicking on Real-Time then Events and finally on YouTube Video Engagement Event as shown below

Congratulations!!! you did it. Just Publish the changes from Google Tag Manager and you are good to go.

In case you have any suggestions or are stuck at any point, feel free to comment here.

Faisal Ahmed

Every brand has stories to tell - stories that will not only engage, inform, surprise, delight, and impact their audience, but that will also deliver on measurable business goals. My job is to turn these brand stories into profitability by measuring action insights & user behaviors.