-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathluna-youtube-tracking.json
186 lines (186 loc) · 17.4 KB
/
luna-youtube-tracking.json
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
{
"exportFormatVersion": 1.3,
"exportTime": "2015-10-16 19:22:13",
"containerVersion": {
"accountId": "28896164",
"containerId": "1638837",
"containerVersionId": "0",
"deleted": false,
"container": {
"accountId": "28896164",
"containerId": "1638837",
"name": "YouTube Tracking",
"publicId": "GTM-MGHN6W",
"timeZoneCountryId": "US",
"timeZoneId": "America/Los_Angeles",
"notes": "",
"usageContext": ["WEB"],
"fingerprint": "1445023325858",
"enabledBuiltInVariable": ["DEBUG_MODE"]
},
"tag": [{
"accountId": "28896164",
"containerId": "1638837",
"tagId": "1",
"name": "CU - YouTube Tracking - LunaMetrics Plugin",
"type": "html",
"liveOnly": false,
"parameter": [{
"type": "BOOLEAN",
"key": "supportDocumentWrite",
"value": "false"
}, {
"type": "TEMPLATE",
"key": "html",
"value": "<script type=\"text/javascript\" id=\"gtm-youtube-tracking\">\n(function(document, window, config) {\n\n 'use strict';\n\t// This script won't work on IE 6 or 7, so we bail at this point if we detect that UA\n\tif (navigator.userAgent.match(/MSIE [67]\\./gi)) return;\n\n var _config = config || {};\n var forceSyntax = _config.forceSyntax || 0;\n var dataLayerName = _config.dataLayerName || 'dataLayer';\n // Default configuration for events\n var eventsFired = {\n 'Play': true,\n 'Pause': true,\n 'Watch to End': true\n };\n\tvar firstScriptTag;\n\tvar tag;\n var key;\n\n for (key in _config.events) {\n\n if (_config.events.hasOwnProperty(key)) {\n\n eventsFired[key] = _config.events[key];\n\n }\n\n }\n\n\tif (window.YT) {\n\n\t\tinit();\t\n\n\t} else {\n\n\t\t// Fetches YouTube JS API\n\t\ttag = document.createElement('script');\n\t\ttag.src = '//www.youtube.com/iframe_api';\n\t\tfirstScriptTag = document.getElementsByTagName('script')[0];\n\t\tfirstScriptTag.parentNode.insertBefore(tag, firstScriptTag);\n\n\t\twindow.onYouTubeIframeAPIReady = (function(o) {\n\n\t\t\treturn function() {\n\n\t\t\t\tif (o) o.apply(this, arguments);\n\n\t\t\t\tinit();\n\n\t\t\t};\t\n\n\t\t})(window.onYouTubeIframeAPIReady);\n\n\t}\n\n // Invoked by the YouTube API when it's ready\n function init() {\n\n\t\tif (document.readyState !== 'loading') {\n\n\t\t\tbind();\n\n\t\t} else {\n\n\t\t\t// On IE8 this fires on window.load, all other browsers will fire when DOM ready\n\t\t\tif ('addEventListener' in document) {\n\n\t\t\t\taddEvent(document, 'DOMContentLoaded', bind);\n\n\t\t\t} else {\n\n\t\t\t\taddEvent(window, 'load', bind);\n\n\t\t\t}\n\n\t\t}\n\n }\n\n\tfunction bind() {\n\n var potentialVideos = getTagsAsArr_('iframe').concat(getTagsAsArr_('embed'));\n digestPotentialVideos(potentialVideos);\n\n // Will bind to dynamically added videos\n if ('addEventListener' in document) { \n document.addEventListener('load', bindToNewVideos_, true);\n }\n\n\t}\n\n // Take our videos and turn them into trackable videos with events\n function digestPotentialVideos(potentialVideos) {\n\n var i;\n\n for (i = 0; i < potentialVideos.length; i++) {\n\n var isYouTubeVideo = checkIfYouTubeVideo(potentialVideos[i]);\n\n if (isYouTubeVideo) {\n\n var normalizedYouTubeIframe = normalizeYouTubeIframe(potentialVideos[i]);\n addYouTubeEvents(normalizedYouTubeIframe);\n\n }\n\n }\n\n }\n\n // Determine if the element is a YouTube video or not\n function checkIfYouTubeVideo(potentialYouTubeVideo) {\n\n var potentialYouTubeVideoSrc = potentialYouTubeVideo.src || '';\n var dataSrc = potentialYouTubeVideo.getAttribute('data-src') || '';\n\n if (potentialYouTubeVideoSrc.indexOf('youtube.com/embed/') > -1 ||\n potentialYouTubeVideoSrc.indexOf('youtube.com/v/') > -1 ||\n dataSrc.indexOf('youtube.com/embed/') > -1 ||\n dataSrc.indexOf('youtube.com/v/') > -1) {\n\n return true;\n\n }\n\n return false;\n\n }\n\n function jsApiEnabled(url) {\n\n return url.indexOf('enablejsapi') > -1;\n\n }\n\n function originEnabled(url) {\n\n return url.indexOf('origin') > -1;\n\n }\n\n // Turn embed objects into iframe objects and ensure they have the right parameters\n function normalizeYouTubeIframe(youTubeVideo) {\n\n var loc = window.location;\n var a = document.createElement('a');\n a.href = youTubeVideo.getAttribute('data-src') || youTubeVideo.src;\n var tmpPathname = a.pathname.charAt(0) === '/' ? a.pathname : '/' + a.pathname; // IE10 shim\n\n // For security reasons, YouTube wants an origin parameter set that matches our hostname\n\n if (!jsApiEnabled(a.search)) {\n\n a.search = (a.search.length > 0 ? a.search + '&' : '') + 'enablejsapi=1';\n\n }\n\n if (!originEnabled(a.search) && loc.hostname.indexOf('localhost') === -1) {\n \n var port = loc.port ? ':' + loc.port : '';\n var origin = loc.protocol + '%2F%2F' + loc.hostname + port;\n\n a.search = a.search + '&origin=' + origin;\n\n }\n\n if (youTubeVideo.type === 'application/x-shockwave-flash') {\n\n var newIframe = document.createElement('iframe');\n newIframe.height = youTubeVideo.height;\n newIframe.width = youTubeVideo.width;\n tmpPathname = tmpPathname.replace('/v/', '/embed/');\n\n youTubeVideo.parentNode.parentNode.replaceChild(newIframe, youTubeVideo.parentNode);\n\n youTubeVideo = newIframe;\n\n }\n\n a.pathname = tmpPathname;\n\n if (youTubeVideo.src !== a.href + a.hash) {\n\n youTubeVideo.src = a.href + a.hash;\n\n }\n\n return youTubeVideo;\n\n }\n\n // Add event handlers for events emitted by the YouTube API\n function addYouTubeEvents(youTubeIframe) {\n\n var player = YT.get(youTubeIframe.id);\n\n if (!player) {\n\n player = new YT.Player(youTubeIframe, {}); \n\n }\n\n if (typeof youTubeIframe.pauseFlag === 'undefined') { \n\n youTubeIframe.pauseFlag = false;\n player.addEventListener('onStateChange', function(evt) {\n\n onStateChangeHandler(evt, youTubeIframe);\n\n });\n\n }\n\n }\n\n // Returns key/value pairs of percentages: number of seconds to achieve\n function getMarks(duration) {\n\n var marks = {};\n\n // For full support, we're handling Watch to End with percentage viewed\n if (_config.events['Watch to End']) {\n\n marks['Watch to End'] = Math.min(duration - 3, Math.floor(duration * 0.99));\n\n }\n\n if (_config.percentageTracking) {\n\n var points = [];\n var i;\n\n if (_config.percentageTracking.each) {\n\n points = points.concat(_config.percentageTracking.each);\n\n }\n\n if (_config.percentageTracking.every) {\n\n var every = parseInt(_config.percentageTracking.every, 10);\n var num = 100 / every;\n\n for (i = 1; i < num; i++) {\n\n points.push(i * every);\n\n }\n\n }\n\n for (i = 0; i < points.length; i++) {\n\n var _point = points[i];\n var _mark = _point + '%';\n var _time = duration * _point / 100;\n\n marks[_mark] = Math.floor(_time);\n\n }\n\n }\n\n return marks;\n\n }\n\n function checkCompletion(player, marks, videoId) {\n\n var currentTime = player.getCurrentTime();\n var key;\n\n player[videoId] = player[videoId] || {};\n\n for (key in marks) {\n\n if (marks[key] <= currentTime && !player[videoId][key]) {\n\n player[videoId][key] = true;\n fireAnalyticsEvent(videoId, key);\n\n }\n\n }\n\n }\n\n // Event handler for events emitted from the YouTube API\n function onStateChangeHandler(evt, youTubeIframe) {\n\n var stateIndex = evt.data;\n var player = evt.target;\n var targetVideoUrl = player.getVideoUrl();\n var targetVideoId = targetVideoUrl.match(/[?&]v=([^&#]*)/)[1]; // Extract the ID \n var playerState = player.getPlayerState();\n var duration = Math.floor(player.getDuration());\n var marks = getMarks(duration);\n var playerStatesIndex = {\n '1': 'Play',\n '2': 'Pause'\n };\n var state = playerStatesIndex[stateIndex];\n\n youTubeIframe.playTracker = youTubeIframe.playTracker || {};\n\n if (playerState === 1 && !youTubeIframe.timer) {\n\n clearInterval(youTubeIframe.timer);\n\n youTubeIframe.timer = setInterval(function() {\n\n // Check every second to see if we've hit any of our percentage viewed marks\n checkCompletion(player, marks, youTubeIframe.videoId);\n\n }, 1000);\n\n } else {\n\n clearInterval(youTubeIframe.timer);\n youTubeIframe.timer = false;\n\n }\n\n // Playlist edge-case handler\n if (stateIndex === 1) {\n\n youTubeIframe.playTracker[targetVideoId] = true;\n youTubeIframe.videoId = targetVideoId;\n youTubeIframe.pauseFlag = false;\n\n }\n\n if (!youTubeIframe.playTracker[youTubeIframe.videoId]) {\n\n // This video hasn't started yet, so this is spam\n return false;\n\n }\n\n if (stateIndex === 2) {\n\n if (!youTubeIframe.pauseFlag) {\n\n youTubeIframe.pauseFlag = true;\n\n } else {\n\n // We don't want to fire consecutive pause events\n return false;\n\n }\n\n }\n\n // If we're meant to track this event, fire it\n if (eventsFired[state]) {\n\n fireAnalyticsEvent(youTubeIframe.videoId, state);\n\n }\n\n }\n\n // Fire an event to Google Analytics or Google Tag Manager\n function fireAnalyticsEvent(videoId, state) {\n\n var videoUrl = 'https://www.youtube.com/watch?v=' + videoId;\n var _ga = window.GoogleAnalyticsObject;\n\n if (typeof window[dataLayerName] !== 'undefined' && !_config.forceSyntax) {\n\n window[dataLayerName].push({\n\n 'event': 'youTubeTrack',\n 'attributes': {\n\n 'videoUrl': videoUrl,\n 'videoAction': state\n\n }\n\n });\n\n } else if (typeof window[_ga] === 'function' &&\n typeof window[_ga].getAll === 'function' &&\n _config.forceSyntax !== 2) {\n\n window[_ga]('send', 'event', 'Videos', state, videoUrl);\n\n } else if (typeof window._gaq !== 'undefined' && forceSyntax !== 1) {\n\n window._gaq.push(['_trackEvent', 'Videos', state, videoUrl]);\n\n }\n\n }\n\n // Simple cross-browser event listener\n function addEvent(el, name, fn) {\n\n if (el.addEventListener) {\n\n el.addEventListener(name, fn);\n\n } else if (el.attachEvent) {\n\n el.attachEvent('on' + name, function(evt) {\n\n evt.target = evt.target || evt.srcElement;\n // Call the event to ensure uniform 'this' handling, pass it event\n fn.call(el, evt);\n\n });\n\n } else if (typeof el['on' + name] === 'undefined' || el['on' + name] === null) {\n\n\n el['on' + name] = function(evt) {\n\n evt.target = evt.target || evt.srcElement;\n // Call the event to ensure uniform 'this' handling, pass it event\n fn.call(el, evt);\n\n };\n\n }\n\n }\n\n // Returns array of elements with given tag name\n function getTagsAsArr_(tagName) {\n\n return [].slice.call(document.getElementsByTagName(tagName));\n\n }\n\n function bindToNewVideos_(evt) {\n\n var el = evt.target || evt.srcElement;\n var isYT = checkIfYouTubeVideo(el);\n\n // We only bind to iframes with a YouTube URL with the enablejsapi=1 and \n // origin=<<hostname>> parameters\n if (el.tagName === 'IFRAME' && isYT && jsApiEnabled(el.src) && originEnabled(el.src)) {\n\n addYouTubeEvents(el);\n\n }\n\n }\n\n})(document, window, {\n 'events': {\n 'Play': true,\n 'Pause': true,\n 'Watch to End': true\n },\n 'percentageTracking': {\n 'every': 25,\n 'each': [10, 90]\n }\n});\n/*\n * Configuration Details\n *\n * @property events object\n * Defines which events emitted by YouTube API\n * will be turned into Google Analytics or GTM events\n *\n * @property percentageTracking object\n * Object with configurations for percentage viewed events\n *\n * @property each array\n * Fires an event once each percentage ahs been reached\n *\n * @property every number\n * Fires an event for every n% viewed\n *\n * @property forceSyntax int 0, 1, or 2\n * Forces script to use Classic (2) or Universal(1)\n *\n * @property dataLayerName string\n * Tells script to use custom dataLayer name instead of default\n */\n/*\n * v8.1.4\n * Created by the Google Analytics consultants at http://www.lunametrics.com\n * Written by @SayfSharif and @notdanwilkerson\n * Documentation: https://github.com/lunametrics/youtube-google-analytics/\n * Licensed under the Creative Commons 4.0 Attribution Public License\n */\n</script>"
}],
"fingerprint": "0",
"firingTriggerId": ["2147479553"],
"parentFolderId": "2",
"tagFiringOption": "ONCE_PER_EVENT"
}, {
"accountId": "28896164",
"containerId": "1638837",
"tagId": "2",
"name": "GA - Event - YouTube Tracking",
"type": "ua",
"liveOnly": false,
"parameter": [{
"type": "BOOLEAN",
"key": "enableEcommerce",
"value": "false"
}, {
"type": "BOOLEAN",
"key": "setTrackerName",
"value": "false"
}, {
"type": "LIST",
"key": "fieldsToSet",
"list": [{
"type": "MAP",
"map": [{
"type": "TEMPLATE",
"key": "fieldName",
"value": "cookieDomain"
}, {
"type": "TEMPLATE",
"key": "value",
"value": "auto"
}]
}]
}, {
"type": "BOOLEAN",
"key": "doubleClick",
"value": "false"
}, {
"type": "TEMPLATE",
"key": "useDebugVersion",
"value": "{{Debug Mode}}"
}, {
"type": "TEMPLATE",
"key": "trackingId",
"value": "{{YOUR_GA_TRACKING_ID}}"
}, {
"type": "TEMPLATE",
"key": "trackType",
"value": "TRACK_EVENT"
}, {
"type": "BOOLEAN",
"key": "nonInteraction",
"value": "false"
}, {
"type": "BOOLEAN",
"key": "enableLinkId",
"value": "false"
}, {
"type": "TEMPLATE",
"key": "eventLabel",
"value": "{{DLV - attributes.videoUrl}}"
}, {
"type": "TEMPLATE",
"key": "eventAction",
"value": "{{DLV - attributes.videoAction}}"
}, {
"type": "TEMPLATE",
"key": "eventCategory",
"value": "Videos"
}],
"fingerprint": "0",
"firingTriggerId": ["1"],
"parentFolderId": "2",
"tagFiringOption": "ONCE_PER_EVENT"
}],
"fingerprint": "0",
"trigger": [{
"accountId": "28896164",
"containerId": "1638837",
"triggerId": "1",
"name": "Event - YouTube Tracking",
"type": "CUSTOM_EVENT",
"customEventFilter": [{
"type": "EQUALS",
"parameter": [{
"type": "TEMPLATE",
"key": "arg0",
"value": "{{_event}}"
}, {
"type": "TEMPLATE",
"key": "arg1",
"value": "youTubeTrack"
}]
}],
"fingerprint": "1445023325858",
"parentFolderId": "2"
}],
"variable": [{
"accountId": "28896164",
"containerId": "1638837",
"variableId": "1",
"name": "DLV - attributes.videoAction",
"type": "v",
"parameter": [{
"type": "BOOLEAN",
"key": "setDefaultValue",
"value": "false"
}, {
"type": "TEMPLATE",
"key": "name",
"value": "attributes.videoAction"
}, {
"type": "INTEGER",
"key": "dataLayerVersion",
"value": "2"
}],
"fingerprint": "0",
"parentFolderId": "2"
}, {
"accountId": "28896164",
"containerId": "1638837",
"variableId": "2",
"name": "DLV - attributes.videoUrl",
"type": "v",
"parameter": [{
"type": "BOOLEAN",
"key": "setDefaultValue",
"value": "false"
}, {
"type": "TEMPLATE",
"key": "name",
"value": "attributes.videoUrl"
}, {
"type": "INTEGER",
"key": "dataLayerVersion",
"value": "2"
}],
"fingerprint": "0",
"parentFolderId": "2"
}],
"folder": [{
"accountId": "28896164",
"containerId": "1638837",
"folderId": "2",
"name": "LunaMetrics YouTube Tracking Plugin",
"fingerprint": "1445023325286"
}]
}
}