Contents
In today’s Woopra tutorial we’re going to look at how to track YouTube video views in Woopra using GTM.
In order to gain a better understanding of how effective our videos are, we’re going to want to fire an event each time your embedded YouTube video is Played, Paused and Reached the end. This data can then be used to further segment our visitor data and see how each video has or hasn’t contributed to conversion.
Furthermore, there is also the possibility to track each percentage in which a video has been viewed – e.g 25%, 50%, 75%, 90%. Each extra tracking component will fire a new event, so it might not be wise to continue firing events and clutter your Woopra visitor data.
If you’re not sure what Woopra is, check out our Getting started with Woopra guide.
Create the Variables in GTM:
There are 2 DataLayer variables which need to be created – {{videoAction}} and {{videoUrl}}. Both of these are the variables which will record the actions each time the event is fired.
Create the videoAction variable:
In GTM navigate to Variables > Create new Variable
- Variable Type: Data Layer Variable
- Variable Name: videoAction
- DataLayer Variable Name: attributes.videoAction
Create the videoUrl variable:
In GTM navigate to Variables > Create new Variable
- Variable Type: Data Layer Variable
- Variable Name: videoAction
- DataLayer Variable Name: attributes.videoUrl
Create the Trigger in GTM:
The Trigger is the event in which the variable will fire upon. This is the Play, Pause, End of Video and Percentage of view (10%, 50% etc..)
In GTM navigate to Triggers > New Trigger
- Trigger Type: Custom Event
- Trigger Name: Youtube Video Track – Woopra
- Fire On: youTubeTrack
- Fire conditions: Video Action > Matches RegEx > Play|Pause|Watch to End
(NOTE: If you wish to fire the percentage views, update the above to Play|Pause|Watch to End|25%|50%|75%|90%)
Create the Event tag in GTM:
This is the event which will fire each time the trigger conditions are equal to TRUE.
In GTM navigate to Tags > Create new Tag
- Tag Name: Woopra – Video Play
- Tag Type: Custom HTML Tag
- Configure Tag: (Copy paste below script)
- Fire On: Select tag > YouTube Video Track – Woopra (created in previous step)
1 2 3 4 5 6 7 8 |
<script> woopra.track("VideoPlay", { url: window.location.pathname, title: document.title, action: {{videoAction}}, videourl: {{videoUrl}} }); </script> |
Create the Script tag in GTM:
Finally we want everything to work, so we need to create one more custom HTML tag which will fire on all pages. This particular script is a modification of a Google Analytics YouTube Tracking script by Lunametrics. The script will detect and enable the tracking of YouTube videos.
If you wish to get specific, you can update your tag to only fire on those pages which have videos.
In GTM navigate to Tags > Create new Tag
- Tag Name: Youtube Tracking Script
- Tag Type: Custom HTML Tag
- Configure Tag: (Copy paste below script)
- Fire On: Select tag > All Pages (or create new custom trigger to only fire on certain pages)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 |
<script type="text/javascript" id="gtm-youtube-tracking"> ;(function( document, window, config ) { 'use strict'; window.onYouTubeIframeAPIReady = (function() { var cached = window.onYouTubeIframeAPIReady; return function() { if( cached ) { cached.apply(this, arguments); } // This script won't work on IE 6 or 7, so we bail at this point if we detect that UA if( !navigator.userAgent.match( /MSIE [67]\./gi ) ) { init(); } }; })(); var _config = config || {}; var forceSyntax = _config.forceSyntax || 0; var dataLayerName = _config.dataLayerName || 'dataLayer'; // Default configuration for events var eventsFired = { 'Play' : true, 'Pause' : true, 'Watch to End': true }; // Overwrites defaults with customizations, if any var key; for( key in _config.events ) { if( _config.events.hasOwnProperty( key ) ) { eventsFired[ key ] = _config.events[ key ]; } } //*****// // DO NOT EDIT ANYTHING BELOW THIS LINE EXCEPT CONFIG AT THE BOTTOM //*****// // Invoked by the YouTube API when it's ready function init() { var iframes = document.getElementsByTagName( 'iframe' ); var embeds = document.getElementsByTagName( 'embed' ); digestPotentialVideos( iframes ); digestPotentialVideos( embeds ); } var tag = document.createElement( 'script' ); tag.src = '//www.youtube.com/iframe_api'; var firstScriptTag = document.getElementsByTagName( 'script' )[0]; firstScriptTag.parentNode.insertBefore( tag, firstScriptTag ); // Take our videos and turn them into trackable videos with events function digestPotentialVideos( potentialVideos ) { var i; for( i = 0; i < potentialVideos.length; i++ ) { var isYouTubeVideo = checkIfYouTubeVideo( potentialVideos[ i ] ); if( isYouTubeVideo ) { var normalizedYouTubeIframe = normalizeYouTubeIframe( potentialVideos[ i ] ); addYouTubeEvents( normalizedYouTubeIframe ); } } } // Determine if the element is a YouTube video or not function checkIfYouTubeVideo( potentialYouTubeVideo ) { var potentialYouTubeVideoSrc = potentialYouTubeVideo.src || ''; if( potentialYouTubeVideoSrc.indexOf( 'youtube.com/embed/' ) > -1 || potentialYouTubeVideoSrc.indexOf( 'youtube.com/v/' ) > -1 ) { return true; } return false; } // Turn embed objects into iframe objects and ensure they have the right parameters function normalizeYouTubeIframe( youTubeVideo ) { var a = document.createElement( 'a' ); a.href = youTubeVideo.src; a.hostname = 'www.youtube.com'; a.protocol = document.location.protocol; var tmpPathname = a.pathname.charAt( 0 ) === '/' ? a.pathname : '/' + a.pathname; // IE10 shim // For security reasons, YouTube wants an origin parameter set that matches our hostname var origin = window.location.protocol + '%2F%2F' + window.location.hostname + ( window.location.port ? ':' + window.location.port : '' ); if( a.search.indexOf( 'enablejsapi' ) === -1 ) { a.search = ( a.search.length > 0 ? a.search + '&' : '' ) + 'enablejsapi=1'; } // Don't set if testing locally if( a.search.indexOf( 'origin' ) === -1 && window.location.hostname.indexOf( 'localhost' ) === -1 ) { a.search = a.search + '&origin=' + origin; } if( youTubeVideo.type === 'application/x-shockwave-flash' ) { var newIframe = document.createElement( 'iframe' ); newIframe.height = youTubeVideo.height; newIframe.width = youTubeVideo.width; tmpPathname = tmpPathname.replace('/v/', '/embed/'); youTubeVideo.parentNode.parentNode.replaceChild( newIframe, youTubeVideo.parentNode ); youTubeVideo = newIframe; } a.pathname = tmpPathname; if(youTubeVideo.src !== a.href + a.hash) { youTubeVideo.src = a.href + a.hash; } return youTubeVideo; } // Add event handlers for events emitted by the YouTube API function addYouTubeEvents( youTubeIframe ) { youTubeIframe.pauseFlag = false; new YT.Player( youTubeIframe, { events: { onStateChange: function( evt ) { onStateChangeHandler( evt, youTubeIframe ); } } } ); } // Returns key/value pairs of percentages: number of seconds to achieve function getMarks(duration) { var marks = {}; // For full support, we're handling Watch to End with percentage viewed if (_config.events[ 'Watch to End' ] ) { marks[ 'Watch to End' ] = duration * 99 / 100; } if( _config.percentageTracking ) { var points = []; var i; if( _config.percentageTracking.each ) { points = points.concat( _config.percentageTracking.each ); } if( _config.percentageTracking.every ) { var every = parseInt( _config.percentageTracking.every, 10 ); var num = 100 / every; for( i = 1; i < num; i++ ) { points.push(i * every); } } for(i = 0; i < points.length; i++) { var _point = points[i]; var _mark = _point + '%'; var _time = duration * _point / 100; marks[_mark] = Math.floor( _time ); } } return marks; } function checkCompletion(player, marks, videoId) { var duration = player.getDuration(); var currentTime = player.getCurrentTime(); var playbackRate = player.getPlaybackRate(); player[videoId] = player[videoId] || {}; var key; for( key in marks ) { if( marks[key] <= currentTime && !player[videoId][key] ) { player[videoId][key] = true; fireAnalyticsEvent( videoId, key ); } } } // Event handler for events emitted from the YouTube API function onStateChangeHandler( evt, youTubeIframe ) { var stateIndex = evt.data; var player = evt.target; var targetVideoUrl = player.getVideoUrl(); var targetVideoId = targetVideoUrl.match( /[?&]v=([^&#]*)/ )[ 1 ]; // Extract the ID var playerState = player.getPlayerState(); var duration = player.getDuration(); var marks = getMarks(duration); var playerStatesIndex = { '1' : 'Play', '2' : 'Pause' }; var state = playerStatesIndex[ stateIndex ]; youTubeIframe.playTracker = youTubeIframe.playTracker || {}; if( playerState === 1 && !youTubeIframe.timer ) { clearInterval(youTubeIframe.timer); youTubeIframe.timer = setInterval(function() { // Check every second to see if we've hit any of our percentage viewed marks checkCompletion(player, marks, youTubeIframe.videoId); }, 1000); } else { clearInterval(youTubeIframe.timer); youTubeIframe.timer = false; } // Playlist edge-case handler if( stateIndex === 1 ) { youTubeIframe.playTracker[ targetVideoId ] = true; youTubeIframe.videoId = targetVideoId; youTubeIframe.pauseFlag = false; } if( !youTubeIframe.playTracker[ youTubeIframe.videoId ] ) { // This video hasn't started yet, so this is spam return false; } if( stateIndex === 2 ) { if( !youTubeIframe.pauseFlag ) { youTubeIframe.pauseFlag = true; } else { // We don't want to fire consecutive pause events return false; } } // If we're meant to track this event, fire it if( eventsFired[ state ] ) { fireAnalyticsEvent( youTubeIframe.videoId, state ); } } // Fire an event to Google Tag Manager function fireAnalyticsEvent( videoId, state ) { var videoUrl = 'https://www.youtube.com/watch?v=' + videoId; if( typeof window[ dataLayerName ] !== 'undefined' && !_config.forceSyntax ) { window[ dataLayerName ].push( { 'event' : 'youTubeTrack', 'attributes': { 'videoUrl': videoUrl, 'videoAction': state } } ); } } } )( document, window, { 'events': { 'Play': true, 'Pause': true, 'Watch to End': true }, 'percentageTracking': { 'every': 25, 'each': [ 10, 90 ] } } ); /* * Configuration Details * * @property events object * Defines which events emitted by YouTube API * will be turned into Google Analytics or GTM events * * @property percentageTracking object * Object with configurations for percentage viewed events * * @property each array * Fires an event once each percentage ahs been reached * * @property every number * Fires an event for every n% viewed * * @property forceSyntax int 0, 1, or 2 * Forces script to use Classic (2) or Universal(1) * * @property dataLayerName string * Tells script to use custom dataLayer name instead of default */ /* * v8.0.4 * Created by the Google Analytics consultants at http://www.lunametrics.com * Written by @SayfSharif and @notdanwilkerson * Documentation: https://github.com/lunametrics/youtube-google-analytics/ * Licensed under the Creative Commons 4.0 Attribution Public License */ </script> |
Update your schema in Woopra:
In Woopra, navigate to Project Settings > Schema > Action Data Schema and create a new action schema with the event info for your video.
That’s it, you’re done! You should now be able to track YouTube video views in Woopra against a visitors activity. To test you can open up a page on your website, play a video and see if the new events appear within Woopra.
(NOTE: Don’t forget to publish your GTM container once all changes have been completed.)
Hope you enjoyed reading – please leave any questions or comments below 🙂
Hello It didn’t work and I think it is because I didn’t know how define the event template. Could you help me with this please?
Hi Andrea,
It would be best to first test that the GTM tag is firing – you can do this by opening GTM and entering “Preview” mode. Once in preview mode, you can browse to a page on your website that has an embedded video to test if the play/pause and other events are being fired.
Best,
MooMaster
Now we have inbuild Youtube tracking in GTM?
What things need to change now?
Hi Akshat,
You’re right, as it is already built in, this would no longer be required. Unless of course you wish to add some additional customization’s to the javascript used in the tracking itself.
Best,
MooMaster