-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyoutube-tracking-script.js
428 lines (285 loc) · 10.1 KB
/
youtube-tracking-script.js
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// Respectfully copied and modified from
// https://github.com/lunametrics/youtube-google-analytics
//
// Original implementation by LunaMetrics
var ytTracker = (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 ) {
// Exclude already decorated videos
if (potentialYouTubeVideo.getAttribute('data-gtm-yt')) {
return false;
}
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;
}
youTubeVideo.setAttribute('data-gtm-yt', 'true');
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();
var targetVideoTitle = player.getVideoData().title;
player[videoId] = player[videoId] || {};
var key;
for( key in marks ) {
if( marks[key] <= currentTime && !player[videoId][key] ) {
player[videoId][key] = true;
fireAnalyticsEvent( videoId, key, targetVideoTitle );
}
}
}
// 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 targetVideoTitle = player.getVideoData().title;
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, targetVideoTitle );
}
}
// Fire an event to Google Analytics or Google Tag Manager
function fireAnalyticsEvent( videoId, state, title ) {
var videoUrl = 'https://www.youtube.com/watch?v=' + videoId;
var videoTitle = title;
var _ga = window.GoogleAnalyticsObject;
var currentPage = window.location.pathname;
var language;
if ( currentPage.includes('en') ) {
language = 'English';
} else if ( currentPage.includes('fr') ) {
language = 'French';
} else {
language = '';
}
state = state + ' ' + language
if( typeof window[ dataLayerName ] !== 'undefined' && !_config.forceSyntax ) {
window[ dataLayerName ].push( {
'event' : 'youTubeTrack',
'attributes': {
'videoUrl': videoUrl,
'videoTitle': title,
'videoAction': state
}
} );
} else if( typeof window[ _ga ] === 'function' &&
typeof window[ _ga ].getAll === 'function' &&
_config.forceSyntax !== 2 )
{
window[ _ga ]( 'send', 'event', 'Videos', state, videoUrl );
} else if( typeof window._gaq !== 'undefined' && forceSyntax !== 1 ) {
window._gaq.push( [ '_trackEvent', 'Videos', state, videoUrl ] );
}
}
return {
init : init,
digestPotentialVideos : digestPotentialVideos
}
})(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
*/
$(function (){
// Check all videos on the page
function callTracker(){
if((typeof YT !== "undefined") && YT && YT.Player){
ytTracker.init();
} else {
setTimeout( callTracker, 500 );
}
}
});