-
Notifications
You must be signed in to change notification settings - Fork 310
/
autotrack.js
519 lines (461 loc) · 19.3 KB
/
autotrack.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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
import { _ } from './utils';
// specifying these locally here since some websites override the global Node var
// ex: https://www.codingame.com/
var ELEMENT_NODE = 1;
var TEXT_NODE = 3;
var autotrack = {
_initializedTokens: [],
_previousElementSibling: function(el) {
if (el.previousElementSibling) {
return el.previousElementSibling;
} else {
do {
el = el.previousSibling;
} while (el && el.nodeType !== ELEMENT_NODE);
return el;
}
},
_loadScript: function(scriptUrlToLoad, callback) {
var scriptTag = document.createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.src = scriptUrlToLoad;
scriptTag.onload = callback;
var scripts = document.getElementsByTagName('script');
if (scripts.length > 0) {
scripts[0].parentNode.insertBefore(scriptTag, scripts[0]);
} else {
document.body.appendChild(scriptTag);
}
},
_getClassName: function(elem) {
switch(typeof elem.className) {
case 'string':
return elem.className;
case 'object': // handle cases where className might be SVGAnimatedString or some other type
return elem.className.baseVal || elem.getAttribute('class') || '';
default: // future proof
return '';
}
},
_getPropertiesFromElement: function(elem) {
var props = {
'classes': this._getClassName(elem).split(' '),
'tag_name': elem.tagName.toLowerCase()
};
if (this._includeField(elem)) {
if (_.includes(['input', 'select', 'textarea'], elem.tagName.toLowerCase())) {
var formFieldValue = this._getFormFieldValue(elem);
if (this._includeFieldValue(formFieldValue)) {
props['value'] = formFieldValue;
}
}
_.each(elem.attributes, function(attr) {
if (this._includeFieldValue(attr.value)) {
props['attr__' + attr.name] = attr.value;
}
}, this);
}
var nthChild = 1;
var nthOfType = 1;
var currentElem = elem;
while (currentElem = this._previousElementSibling(currentElem)) { // eslint-disable-line no-cond-assign
nthChild++;
if (currentElem.tagName === elem.tagName) {
nthOfType++;
}
}
props['nth_child'] = nthChild;
props['nth_of_type'] = nthOfType;
return props;
},
/*
* Due to potential reference discrepancies (such as the webcomponents.js polyfill)
* We want to match tagNames instead of specific reference because something like element === document.body
* won't always work because element might not be a native element.
*/
_isTag: function(el, tag) {
return el && el.tagName && el.tagName.toLowerCase() === tag.toLowerCase();
},
_shouldTrackDomEvent: function(element, event) {
if (!element || this._isTag(element, 'html') || element.nodeType !== ELEMENT_NODE) {
return false;
}
var tag = element.tagName.toLowerCase();
switch (tag) {
case 'html':
return false;
case 'form':
return event.type === 'submit';
case 'input':
if (['button', 'submit'].indexOf(element.getAttribute('type')) === -1) {
return event.type === 'change';
} else {
return event.type === 'click';
}
case 'select':
case 'textarea':
return event.type === 'change';
default:
return event.type === 'click';
}
},
_getDefaultProperties: function(eventType) {
return {
'$event_type': eventType,
'$ce_version': 1,
'$host': window.location.host,
'$pathname': window.location.pathname
};
},
_getInputValue: function(input) {
var value = null;
var type = input.type.toLowerCase();
switch(type) {
case 'checkbox':
if (input.checked) {
value = [input.value];
}
break;
case 'radio':
if (input.checked) {
value = input.value;
}
break;
default:
value = input.value;
break;
}
return value;
},
_getSelectValue: function(select) {
var value;
if (select.multiple) {
var values = [];
_.each(select.querySelectorAll('[selected]'), function(option) {
values.push(option.value);
});
value = values;
} else {
value = select.value;
}
return value;
},
_includeField: function(input) {
for (var curEl = input; curEl.parentNode && !this._isTag(curEl, 'body'); curEl = curEl.parentNode) {
var classes = this._getClassName(curEl).split(' ');
if (_.includes(classes, 'mp-sensitive') || _.includes(classes, 'mp-no-track')) {
return false;
}
}
if (_.includes(this._getClassName(input).split(' '), 'mp-include')) {
return true;
}
// don't include hidden or password fields
var type = input.type || '';
switch(type.toLowerCase()) {
case 'hidden':
return false;
case 'password':
return false;
}
// filter out data from fields that look like sensitive fields
var name = input.name || input.id || '';
var sensitiveNameRegex = /^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|seccode|securitycode|securitynum|socialsec|socsec|ssn/i;
if (sensitiveNameRegex.test(name.replace(/[^a-zA-Z0-9]/g, ''))) {
return false;
}
return true;
},
_includeFieldValue: function(value) {
if (value === null) {
return false;
}
if (typeof value === 'string') {
// check to see if input value looks like a credit card number
// see: https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s20.html
var ccRegex = /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/;
if (ccRegex.test((value || '').replace(/[\- ]/g, ''))) {
return false;
}
// check to see if input value looks like a social security number
var ssnRegex = /(^\d{3}-?\d{2}-?\d{4}$)/;
if (ssnRegex.test(value)) {
return false;
}
}
return true;
},
_getFormFieldValue: function(field) {
var val;
switch(field.tagName.toLowerCase()) {
case 'input':
val = this._getInputValue(field);
break;
case 'select':
val = this._getSelectValue(field);
break;
default:
val = field.value || field.textContent;
break;
}
return this._includeField(field) && this._includeFieldValue(val) ? val : null;
},
_getFormFieldProperties: function(form) {
var formFieldProps = {};
_.each(form.elements, function(field) {
var name = field.getAttribute('name') || field.getAttribute('id');
if (name !== null) {
name = '$form_field__' + name;
var val = this._getFormFieldValue(field);
if (this._includeField(field) && this._includeFieldValue(val)) {
var prevFieldVal = formFieldProps[name];
if (prevFieldVal !== undefined) { // combine values for inputs of same name
formFieldProps[name] = [].concat(prevFieldVal, val);
} else {
formFieldProps[name] = val;
}
}
}
}, this);
return formFieldProps;
},
_extractCustomPropertyValue: function(customProperty) {
var propValues = [];
_.each(document.querySelectorAll(customProperty['css_selector']), function(matchedElem) {
if (['input', 'select'].indexOf(matchedElem.tagName.toLowerCase()) > -1) {
propValues.push(matchedElem['value']);
} else if (matchedElem['textContent']) {
propValues.push(matchedElem['textContent']);
}
});
return propValues.join(', ');
},
_getCustomProperties: function(targetElementList) {
var props = {};
_.each(this._customProperties, function(customProperty) {
_.each(customProperty['event_selectors'], function(eventSelector) {
var eventElements = document.querySelectorAll(eventSelector);
_.each(eventElements, function(eventElement) {
if (_.includes(targetElementList, eventElement)) {
props[customProperty['name']] = this._extractCustomPropertyValue(customProperty);
}
}, this);
}, this);
}, this);
return props;
},
_getEventTarget: function(e) {
// https://developer.mozilla.org/en-US/docs/Web/API/Event/target#Compatibility_notes
if (typeof e.target === 'undefined') {
return e.srcElement;
} else {
return e.target;
}
},
_trackEvent: function(e, instance) {
/*** Don't mess with this code without running IE8 tests on it ***/
var target = this._getEventTarget(e);
if (target.nodeType === TEXT_NODE) { // defeat Safari bug (see: http://www.quirksmode.org/js/events_properties.html)
target = target.parentNode;
}
if (this._shouldTrackDomEvent(target, e)) {
var targetElementList = [target];
var curEl = target;
while (curEl.parentNode && !this._isTag(curEl, 'body')) {
targetElementList.push(curEl.parentNode);
curEl = curEl.parentNode;
}
var elementsJson = [];
var href, elementText, form, explicitNoTrack = false;
_.each(targetElementList, function(el, idx) {
// if the element or a parent element is an anchor tag
// include the href as a property
if (el.tagName.toLowerCase() === 'a') {
href = el.getAttribute('href');
} else if (el.tagName.toLowerCase() === 'form') {
form = el;
}
// crawl up to max of 5 nodes to populate text content
if (!elementText && idx < 5 && el.textContent) {
var textContent = _.trim(el.textContent);
if (textContent) {
elementText = textContent.replace(/[\r\n]/g, ' ').replace(/[ ]+/g, ' ').substring(0, 255);
}
}
// allow users to programatically prevent tracking of elements by adding class 'mp-no-track'
var classes = this._getClassName(el).split(' ');
if (_.includes(classes, 'mp-no-track')) {
explicitNoTrack = true;
}
elementsJson.push(this._getPropertiesFromElement(el));
}, this);
if (explicitNoTrack) {
return false;
}
var props = _.extend(
this._getDefaultProperties(e.type),
{
'$elements': elementsJson,
'$el_attr__href': href,
'$el_text': elementText
},
this._getCustomProperties(targetElementList)
);
if (form && (e.type === 'submit' || e.type === 'click')) {
_.extend(props, this._getFormFieldProperties(form));
}
instance.track('$web_event', props);
return true;
}
},
// only reason is to stub for unit tests
// since you can't override window.location props
_navigate: function(href) {
window.location.href = href;
},
_addDomEventHandlers: function(instance) {
var handler = _.bind(function(e) {
e = e || window.event;
this._trackEvent(e, instance);
}, this);
_.register_event(document, 'submit', handler, false, true);
_.register_event(document, 'change', handler, false, true);
_.register_event(document, 'click', handler, false, true);
},
_customProperties: {},
init: function(instance) {
if (!(document && document.body)) {
console.log('document not ready yet, trying again in 500 milliseconds...');
var that = this;
setTimeout(function() { that.init(instance); }, 500);
return;
}
var token = instance.get_config('token');
if (this._initializedTokens.indexOf(token) > -1) {
console.log('autotrack already initialized for token "' + token + '"');
return;
}
this._initializedTokens.push(token);
if (!this._maybeLoadEditor(instance)) { // don't autotrack actions when the editor is enabled
var parseDecideResponse = _.bind(function(response) {
if (response && response['config'] && response['config']['enable_collect_everything'] === true) {
if (response['custom_properties']) {
this._customProperties = response['custom_properties'];
}
instance.track('$web_event', _.extend({
'$title': document.title
}, this._getDefaultProperties('pageview')));
this._addDomEventHandlers(instance);
} else {
instance['__autotrack_enabled'] = false;
}
}, this);
instance._send_request(
instance.get_config('api_host') + '/decide/', {
'verbose': true,
'version': '1',
'lib': 'web',
'token': token
},
instance._prepare_callback(parseDecideResponse)
);
}
},
_editorParamsFromHash: function(instance, hash) {
var editorParams;
try {
var state = _.getHashParam(hash, 'state');
state = JSON.parse(decodeURIComponent(state));
var expiresInSeconds = _.getHashParam(hash, 'expires_in');
editorParams = {
'accessToken': _.getHashParam(hash, 'access_token'),
'accessTokenExpiresAt': (new Date()).getTime() + (Number(expiresInSeconds) * 1000),
'bookmarkletMode': !!state['bookmarkletMode'],
'projectId': state['projectId'],
'projectOwnerId': state['projectOwnerId'],
'projectToken': state['token'],
'readOnly': state['readOnly'],
'userFlags': state['userFlags'],
'userId': state['userId']
};
window.sessionStorage.setItem('editorParams', JSON.stringify(editorParams));
if (state['desiredHash']) {
window.location.hash = state['desiredHash'];
} else if (window.history) {
history.replaceState('', document.title, window.location.pathname + window.location.search); // completely remove hash
} else {
window.location.hash = ''; // clear hash (but leaves # unfortunately)
}
} catch (e) {
console.error('Unable to parse data from hash', e);
}
return editorParams;
},
/**
* To load the visual editor, we need an access token and other state. That state comes from one of three places:
* 1. In the URL hash params if the customer is using an old snippet
* 2. From session storage under the key `_mpcehash` if the snippet already parsed the hash
* 3. From session storage under the key `editorParams` if the editor was initialized on a previous page
*/
_maybeLoadEditor: function(instance) {
try {
var parseFromUrl = false;
if (_.getHashParam(window.location.hash, 'state')) {
var state = _.getHashParam(window.location.hash, 'state');
state = JSON.parse(decodeURIComponent(state));
parseFromUrl = state['action'] === 'mpeditor';
}
var parseFromStorage = !!window.sessionStorage.getItem('_mpcehash');
var editorParams;
if (parseFromUrl) { // happens if they are initializing the editor using an old snippet
editorParams = this._editorParamsFromHash(instance, window.location.hash);
} else if (parseFromStorage) { // happens if they are initialized the editor and using the new snippet
editorParams = this._editorParamsFromHash(instance, window.sessionStorage.getItem('_mpcehash'));
window.sessionStorage.removeItem('_mpcehash');
} else { // get credentials from sessionStorage from a previous initialzation
editorParams = JSON.parse(window.sessionStorage.getItem('editorParams') || '{}');
}
if (editorParams['projectToken'] && instance.get_config('token') === editorParams['projectToken']) {
this._loadEditor(instance, editorParams);
return true;
} else {
return false;
}
} catch (e) {
return false;
}
},
_loadEditor: function(instance, editorParams) {
if (!window['_mpEditorLoaded']) { // only load the codeless event editor once, even if there are multiple instances of MixpanelLib
window['_mpEditorLoaded'] = true;
var editorUrl = instance.get_config('app_host')
+ '/js-bundle/reports/collect-everything/editor.js?_ts='
+ (new Date()).getTime();
this._loadScript(editorUrl, function() {
window['mp_load_editor'](editorParams);
});
return true;
}
return false;
},
// this is a mechanism to ramp up CE with no server-side interaction.
// when CE is active, every page load results in a decide request. we
// need to gently ramp this up so we don't overload decide. this decides
// deterministically if CE is enabled for this project by modding the char
// value of the project token.
enabledForProject: function(token, numBuckets, numEnabledBuckets) {
numBuckets = !_.isUndefined(numBuckets) ? numBuckets : 10;
numEnabledBuckets = !_.isUndefined(numEnabledBuckets) ? numEnabledBuckets : 10;
var charCodeSum = 0;
for (var i = 0; i < token.length; i++) {
charCodeSum += token.charCodeAt(i);
}
return (charCodeSum % numBuckets) < numEnabledBuckets;
},
isBrowserSupported: function() {
return _.isFunction(document.querySelectorAll);
}
};
_.bind_instance_methods(autotrack);
_.safewrap_instance_methods(autotrack);
export { autotrack };