Tracking Plays of Embedded YouTube Videos

YouTube has become an incredibly popular way to communicate information. From promotional videos to demonstrations to “thank you” messages, YouTube has revolutionized mass communication, and it is here to stay. But did you know that you can use web tracking to determine if someone has played a YouTube video on your website? With some knowledge of JavaScript, you’ll be on your way to tracking your videos so you can tell if you’re going viral!

The JavaScript know-how you’ll need to make this work is described below. Additionally, you’ll need the ability to make changes to your website.

Steps

Many YouTube videos are embedded using iFrames. To track YouTube views, you can use YouTube’s iFrame API.

First, add the normal Informz Web Tracking Code to the bottom of the web page containing the embedded YouTube video.

At the top of that web page, include the following script:

<script src="https://www.youtube.com/iframe_api"></script>

Add the following code where you would normally add iFrame code:

<div id='vidWrapper'> 
<!-- The <iframe> (and video player) will replace this <div> tag. --> 
<div id="ytplayer"></div> 
</div> 

Finally, you’ll need to include code to receive the Play action from YouTube. This way, whenever someone plays a video on your site (by clicking the Play button), you’ll see a web tracking result. Add the following code and make sure you enter the correct video ID:

<script> 
var player; 

function onYouTubeIframeAPIReady() { 
player = new YT.Player('ytplayer', { 
height: '315', 
width: '560', 
videoId: 'f2iET4Phh4s', // change this to the correct video id 
events: { 
'onStateChange': function(event) { 
if (event.data == YT.PlayerState.PLAYING) { 
informz_trk('trackStructEvent', 
'Change to something else', 
'Clicked Play on Video', 
'' // Value (Optional) 
); 
} 
} 
} 
}); 
} 
</script> 

That’s all there is to it! Now you’ll see interaction data related to video plays in your Web Tracking Report.

Just Push Play!

Now you have an elegant solution to your YouTube web tracking dilemmas! If you want to be extra certain that your solution works properly, simply add the following code before informz_trk to ensure that everything works when you click play:

alert(‘Hello World’);

Just remember to remove this alert before you publish your code! Also remember that this alert is simply designed to let you know that clicking Play is properly being tracked in your code. It doesn't do anything more than that, so you won't need it once you've tested!