-
Notifications
You must be signed in to change notification settings - Fork 3
/
ajax-event-tracking-lunarmetrics.html
259 lines (198 loc) · 6.47 KB
/
ajax-event-tracking-lunarmetrics.html
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
<!--- jQuery AJAX Form Listener --->
<!--- Vanilla verison below --->
<script id="gtm-jq-ajax-listen" type="text/javascript">
(function() {
'use strict';
var $;
var n = 0;
init();
function init(n) {
// Ensure jQuery is available before anything
if (typeof jQuery !== 'undefined') {
// Define our $ shortcut locally
$ = jQuery;
bindToAjax();
// Check for up to 10 seconds
} else if (n < 20) {
n++;
setTimeout(init, 500);
}
}
function bindToAjax() {
$(document).bind('ajaxComplete', function(evt, jqXhr, opts) {
// Create a fake a element for magically simple URL parsing
var fullUrl = document.createElement('a');
fullUrl.href = opts.url;
// IE9+ strips the leading slash from a.pathname because who wants to get home on time Friday anyways
var pathname = fullUrl.pathname[0] === '/' ? fullUrl.pathname : '/' + fullUrl.pathname;
// Manually remove the leading question mark, if there is one
var queryString = fullUrl.search[0] === '?' ? fullUrl.search.slice(1) : fullUrl.search;
// Turn our params and headers into objects for easier reference
var queryParameters = objMap(queryString, '&', '=', true);
var headers = objMap(jqXhr.getAllResponseHeaders(), '\n', ':');
// Blindly push to the dataLayer because this fires within GTM
dataLayer.push({
'event': 'ajaxComplete',
'attributes': {
// Return empty strings to prevent accidental inheritance of old data
'type': opts.type || '',
'url': fullUrl.href || '',
'queryParameters': queryParameters,
'pathname': pathname || '',
'hostname': fullUrl.hostname || '',
'protocol': fullUrl.protocol || '',
'fragment': fullUrl.hash || '',
'statusCode': jqXhr.status || '',
'statusText': jqXhr.statusText || '',
'headers': headers,
'timestamp': evt.timeStamp || '',
'contentType': opts.contentType || '',
// Defer to jQuery's handling of the response
'response': (jqXhr.responseJSON || jqXhr.responseXML || jqXhr.responseText || '')
}
});
});
}
function objMap(data, delim, spl, decode) {
var obj = {};
// If one of our parameters is missing, return an empty object
if (!data || !delim || !spl) {
return {};
}
var arr = data.split(delim);
var i;
if (arr) {
for (i = 0; i < arr.length; i++) {
// If the decode flag is present, URL decode the set
var item = decode ? decodeURIComponent(arr[i]) : arr[i];
var pair = item.split(spl);
var key = trim_(pair[0]);
var value = trim_(pair[1]);
if (key && value) {
obj[key] = value;
}
}
}
return obj;
}
// Basic .trim() polyfill
function trim_(str) {
if (str) {
return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
}
}
})();
/*
* v0.1.0
* Created by the Google Analytics consultants at http://www.lunametrics.com
* Written by @notdanwilkerson
* Documentation: http://www.lunametrics.com/blog/2015/08/27/ajax-event-listener-google-tag-manager/
* Licensed under the Creative Commons 4.0 Attribution Public License
*/
</script>
<!--- Vanilla JS AJAX Form Listener --->
<script id="gtm-ajax-listener" type="text/javascript">
(function () {
'use strict';
var originalOpen = window.XMLHttpRequest.prototype.open,
originalSend = window.XMLHttpRequest.prototype.send;
function trimSpecialChars(str) {
if (str) {
return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
}
}
function objMap(data, delimiter, splitSeparator, decode) {
if (!data) {
return {};
}
var obj = {};
var arr = data.split(delimiter);
for (var i = 0; i < arr.length; i++) {
var item = decode ? decodeURIComponent(arr[i]) : arr[i];
var pair = item.split(splitSeparator);
var key = trimSpecialChars(pair[0]);
var value = trimSpecialChars(pair[1]);
if (key && value) {
obj[key] = value;
}
}
return obj;
}
function getUrlSegments(url) {
var fakeElement = document.createElement('a');
fakeElement.href = url;
// IE9+ strips the leading slash from a.pathname
var pathName = fakeElement.pathname[0] === '/' ? fakeElement.pathname : '/' + fakeElement.pathname;
var queryString = fakeElement.search[0] === '?' ? fakeElement.search.slice(1) : fakeElement.search;
var queryParameters = objMap(queryString, '&', '=', true);
return {
fullUrl: fakeElement,
hostName: fakeElement.hostname,
protocol: fakeElement.protocol,
pathName: pathName,
queryString: queryString,
queryParameters: queryParameters,
fragment: fakeElement.hash
};
}
function parseJSON(text) {
try {
return JSON.parse(text);
} catch (err) {
return false;
}
}
function pushEvent(xhr) {
var urlSegments = getUrlSegments(xhr.requestUrl);
var headers = objMap(xhr.getAllResponseHeaders(), '\n', ':');
var responseJSON = parseJSON(xhr.responseText);
dataLayer.push({
event: 'ajaxComplete',
attributes: {
// Return empty strings to prevent accidental inheritance of old data
'type': xhr.method || '',
'url': urlSegments.fullUrl || '',
'queryParameters': urlSegments.queryParameters,
'pathname': urlSegments.pathName || '',
'hostname': urlSegments.hostName || '',
'protocol': urlSegments.protocol || '',
'fragment': urlSegments.fragment || '',
'statusCode': xhr.status || '',
'statusText': xhr.statusText || '',
'headers': headers,
'timestamp': (new Date).getTime() || '',
'contentType': headers['content-type'] || '',
'response': (responseJSON ||
((xhr.responseType === '' || xhr.responseType === 'document') && xhr.responseXML) || xhr.responseText || '')
}
});
}
function openRequest() {
this.method = arguments[0];
this.requestUrl = arguments[1];
originalOpen.apply(this, arguments);
}
function sendRequest() {
var originalOnReadyStateChange = this.onreadystatechange || null;
this.onreadystatechange = function () {
if (this.readyState === 4) {
pushEvent(this);
}
if (originalOnReadyStateChange) {
return originalOnReadyStateChange.apply(this, arguments);
}
};
return originalSend.apply(this, arguments);
}
window.XMLHttpRequest.prototype.open = openRequest;
window.XMLHttpRequest.prototype.send = sendRequest;
})();
/*
* v1.0.0
* Modified to work without JQuery or any dependencies by Marko Sulamägi https://gtm.marxdev.com
* Original version created by the Google Analytics consultants at http://www.lunametrics.com
*
* Documentation: https://gtm.marxdev.com
* Licensed under the MIT License
*/
</script>