This repository has been archived by the owner on Apr 28, 2022. It is now read-only.
/
analytics.js
584 lines (477 loc) · 23 KB
/
analytics.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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
(function () {
// A reference to the global object.
var root = this;
// Whether analytics.js has been initialized.
var initialized = false;
// Store the date when the page loaded, for analytics that depend on that.
var date = new Date();
// Store window.onload state so that analytics that rely on it (ffs) can be
// loaded even after it has happened.
var loaded = false;
var oldonload = window.onload;
window.onload = function () {
loaded = true;
if (isFunction(oldonload)) oldonload();
};
var getSeconds = function (time) {
return Math.floor((new Date(time)) / 1000);
};
// A helper to shallow-ly clone objects, so that they don't get mangled or
// added to by different analytics providers because of the reference.
var clone = function (obj) {
if (!obj) return;
var clone = {};
for (var prop in obj) clone[prop] = obj[prop];
return clone;
};
// Type detection helpers, copied from [underscore](https://github.com/documentcloud/underscore/blob/master/underscore.js#L928-L938).
var isObject = function (obj) {
return obj === Object(obj);
};
var isString = function (obj) {
return Object.prototype.toString.call(obj) === '[object String]';
};
var isFunction = function (obj) {
return Object.prototype.toString.call(obj) === '[object Function]';
};
// Email detection helper.
var basicEmailRegex = /.+\@.+\..+/;
var isEmail = function (input) {
return basicEmailRegex.test(input);
};
// A helper to resolve a settings object. It allows for `settings` to be an
// `fieldName` string in the case of no additional settings being needed.
// Field name is the setting for the api key for our shorthand.
var resolveSettings = function (settings, fieldName) {
if (!isString(settings) && !isObject(settings))
throw new Error('Encountered unresolvable settings value.');
if (isString(settings)) {
var apiKey = settings;
settings = {};
settings[fieldName] = apiKey;
}
return settings;
};
// The `analytics` object that will be exposed to you on the global object.
root.analytics || (root.analytics = {
// A list of providers that have been initialized.
providers : [],
// A `userId` to save.
userId : null,
// Initialize
// ==========
// Call **initialize** to setup analytics.js before identifying or
// tracking any users or events. It takes a list of providers that you
// want to enable, along with settings for each provider. (Settings vary
// depending on the provider.) Here's what a call to **initialize**
// might look like:
//
// analytics.initialize({
// 'Google Analytics' : 'UA-XXXXXXX-X',
// 'Segment.io' : 'XXXXXXXXXXX',
// 'KISSmetrics' : 'XXXXXXXXXXX'
// });
//
// `providers` - a dictionary of the providers you want to enabled. The
// keys are the names of the providers and their values are the settings
// they get passed on initialization.
initialize : function (providers) {
this.providers = [];
for (var key in providers) {
if (!availableProviders[key]) throw new Error('Couldn\'t find a provider named "'+key+'"');
availableProviders[key].initialize(providers[key]);
this.providers.push(availableProviders[key]);
}
initialized = true;
},
// Identify
// ========
// Identifying a user ties all of their actions to an ID you recognize
// and records properties about a user. An example identify:
//
// analytics.identify('user@example.com', {
// name : 'Achilles',
// age : 23
// });
//
// `userId` - [optional] the ID you recognize your user by, like an email.
//
// `traits` - an optional dictionary of traits to tie your user. Things
// like *Name*, *Age* or *Friend Count*.
identify : function (userId, traits) {
if (!initialized) return;
if (isObject(userId)) {
traits = userId;
userId = null;
}
// Save it for future use, or use saved userId.
if (userId !== null)
this.userId = userId;
else
userId = this.userId;
for (var i = 0, provider; provider = this.providers[i]; i++) {
if (!provider.identify) continue;
var clonedTraits = clone(traits);
provider.identify(userId, clonedTraits);
}
},
// Track
// =====
// Whenever a visitor triggers an event on your site that you're
// interested in, you'll want to track it. An example track:
//
// analytics.track('Added a Friend', {
// level : 'hard',
// volume : 11
// });
//
// `event` - the name of the event. The best event names are human-
// readable so that your whole team knows what they are when you analyze
// your data.
//
// `properties` - an optional dictionary of properties of the event.
track : function (event, properties) {
if (!initialized) return;
for (var i = 0, provider; provider = this.providers[i]; i++) {
if (!provider.track) continue;
var clonedProperties = clone(properties);
provider.track(event, clonedProperties);
}
}
});
// Providers
// =========
// A list of available providers that _can_ be initialized by you.
var availableProviders = {
// Google Analytics
// ----------------
// _Last updated: October 31st, 2012_
//
// [Documentation](https://developers.google.com/analytics/devguides/collection/gajs/).
'Google Analytics' : {
// Changes to the Google Analytics snippet:
//
// * Added optional support for `enhancedLinkAttribution`
//
// * Added optional support for `siteSpeedSampleRate`
//
// * Add `apiKey` to call to `_setAccount`.
initialize : function (settings) {
this.settings = settings = resolveSettings(settings, 'trackingId');
var _gaq = _gaq || [];
_gaq.push(['_setAccount', settings.trackingId]);
if (this.settings.enhancedLinkAttribution === true) {
var pluginUrl = (('https:' == document.location.protocol) ? 'https://ssl.' : 'http://www.') + 'google-analytics.com/plugins/ga/inpage_linkid.js';
_gaq.push(['_require', 'inpage_linkid', pluginUrl]);
}
if (this.settings.siteSpeedSampleRate != null &&
typeof(this.settings.siteSpeedSampleRate) === 'number') {
_gaq.push(['_setSiteSpeedSampleRate', this.settings.siteSpeedSampleRate]);
}
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
window._gaq = _gaq;
},
track : function (event, properties) {
window._gaq.push(['_trackEvent', 'All', event]);
}
},
// KISSmetrics
// -----------
// _Last updated: September 27th, 2012_
//
// [Documentation](http://support.kissmetrics.com/apis/javascript).
'KISSmetrics' : {
// Changes to the KISSmetrics snippet:
//
// * Concatenate in the `apiKey`.
initialize : function (settings) {
this.settings = settings = resolveSettings(settings, 'apiKey');
var _kmq = _kmq || [];
function _kms(u){
setTimeout(function(){
var d = document, f = d.getElementsByTagName('script')[0],
s = d.createElement('script');
s.type = 'text/javascript'; s.async = true; s.src = u;
f.parentNode.insertBefore(s, f);
}, 1);
}
_kms('//i.kissmetrics.com/i.js');
_kms('//doug1izaerwt3.cloudfront.net/'+ settings.apiKey +'.1.js'); // Add API key from settings.
window._kmq = _kmq;
},
// KISSmetrics uses two separate methods: `identify` for storing the
// `userId` and `set` for storing `traits`.
identify : function (userId, traits) {
if (userId)
window._kmq.push(['identify', userId]);
if (traits)
window._kmq.push(['set', traits]);
},
track : function (event, properties) {
window._kmq.push(['record', event, properties]);
}
},
// Mixpanel
// --------
// _Last updated: September 27th, 2012_
//
// [Documentation](https://mixpanel.com/docs/integration-libraries/javascript),
// [documentation](https://mixpanel.com/docs/people-analytics/javascript),
// [documentation](https://mixpanel.com/docs/integration-libraries/javascript-full-api).
'Mixpanel' : {
// Changes to the Mixpanel snippet:
//
// * Use window for call to `init`.
// * Add `apiKey` and `settings` args to call to `init`.
//
// Also, we don't need to set the `mixpanel` object on `window` because
// they already do that.
initialize : function (settings) {
this.settings = settings = resolveSettings(settings, 'token');
(function(c,a){window.mixpanel=a;var b,d,h,e;b=c.createElement("script");
b.type="text/javascript";b.async=!0;b.src=("https:"===c.location.protocol?"https:":"http:")+
'//cdn.mxpnl.com/libs/mixpanel-2.1.min.js';d=c.getElementsByTagName("script")[0];
d.parentNode.insertBefore(b,d);a._i=[];a.init=function(b,c,f){function d(a,b){
var c=b.split(".");2==c.length&&(a=a[c[0]],b=c[1]);a[b]=function(){a.push([b].concat(
Array.prototype.slice.call(arguments,0)))}}var g=a;"undefined"!==typeof f?g=a[f]=[]:
f="mixpanel";g.people=g.people||[];h=['disable','track','track_pageview','track_links',
'track_forms','register','register_once','unregister','identify','name_tag',
'set_config','people.identify','people.set','people.increment'];for(e=0;e<h.length;e++)d(g,h[e]);
a._i.push([b,c,f])};a.__SV=1.1;})(document,window.mixpanel||[]);
window.mixpanel.init(settings.token, settings);
},
// Only identify with Mixpanel's People feature if you opt-in because
// otherwise Mixpanel charges you for it.
// Alias email -> $email
identify : function (userId, traits) {
if (userId) {
window.mixpanel.identify(userId);
window.mixpanel.name_tag(userId);
if (isEmail(userId)) {
traits = traits || {};
traits.email = userId;
}
}
if (traits) {
this.aliasTraits(traits);
window.mixpanel.register(traits);
}
if (this.settings.people === true) {
if (userId)
window.mixpanel.people.identify(userId);
if (traits)
window.mixpanel.people.set(traits);
}
},
aliasTraits : function (traits) {
if (traits.email) {
traits['$email'] = traits.email;
delete traits.email;
}
if (traits.name) {
traits['$name'] = traits.name;
delete traits.name;
}
if (traits.username) {
traits['$username'] = traits.username;
delete traits.username;
}
if (traits.lastSeen) {
traits['$last_login'] = traits.lastSeen;
delete traits.lastSeen;
}
if (traits.createdAt) {
traits['$created'] = traits.createdAt;
delete traits.createdAt;
}
},
track : function (event, properties) {
window.mixpanel.track(event, properties);
}
},
// Intercom
// --------
// _Last updated: September 27th, 2012_
//
// [Documentation](http://docs.intercom.io/).
'Intercom' : {
// Intercom identifies when the script is loaded, so instead of
// initializing in `initialize`, we have to initialize in `identify`.
initialize: function (settings) {
this.settings = resolveSettings(settings, 'appId');
},
// Changes to the Intercom snippet:
//
// * Add `appId` from stored `settings`.
// * Add `userId`.
identify: function (userId, traits) {
// Don't do anything if we just have traits.
if (!userId) return;
window.intercomSettings = {
app_id : this.settings.appId,
user_id : userId,
custom_data : traits || {},
};
if (traits) {
if (traits.email)
window.intercomSettings.email = traits.email;
if (traits.name)
window.intercomSettings.name = traits.name;
if (traits.createdAt)
window.intercomSettings.created_at = getSeconds(traits.createdAt);
} else if (isEmail(userId)) {
window.intercomSettings.email = userId;
}
function async_load() {
var s = document.createElement('script');
s.type = 'text/javascript'; s.async = true;
s.src = 'https://api.intercom.io/api/js/library.js';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
}
if (window.attachEvent) {
window.attachEvent('onload', async_load);
} else {
window.addEventListener('load', async_load, false);
}
}
},
// Customer.io
// ----------
// _Last updated: December 6th, 2012_
//
// [Documentation](http://customer.io/docs/api/javascript.html).
'Customer.io' : {
initialize : function (settings) {
this.settings = settings = resolveSettings(settings, 'siteId');
var _cio = _cio || [];
(function() {
var a,b,c;a=function(f){return function(){_cio.push([f].
concat(Array.prototype.slice.call(arguments,0)))}};b=["identify",
"track"];for(c=0;c<b.length;c++){_cio[b[c]]=a(b[c])};
var t = document.createElement('script'),
s = document.getElementsByTagName('script')[0];
t.async = true;
t.id = 'cio-tracker';
t.setAttribute('data-site-id', settings.siteId);
t.src = 'https://assets.customer.io/assets/track.js';
s.parentNode.insertBefore(t, s);
})();
window._cio = _cio;
},
identify : function (userId, traits) {
// Don't do anything if we just have traits.
if (!userId) return;
traits = traits || {};
var properties = clone(traits);
properties.id = userId;
if (properties.email === undefined && isEmail(userId))
properties.email = userId;
if (properties.createdAt) {
properties.created_at = getSeconds(properties.createdAt);
delete properties.createdAt;
}
window._cio.identify(properties);
},
track : function (event, properties) {
window._cio.track(event, properties);
}
},
// CrazyEgg.com
// ----------
// _Last updated: December 6th, 2012_
// API Key is the xxxx/xxxx in "//dnn506yrbagrg.cloudfront.net/pages/scripts/xxxx/xxxx.js"
// [Documentation](www.crazyegg.com).
'CrazyEgg' : {
initialize : function (settings) {
this.settings = settings = resolveSettings(settings, 'apiKey');
(function(){
var a=document.createElement("script");
var b=document.getElementsByTagName("script")[0];
a.src=document.location.protocol+"//dnn506yrbagrg.cloudfront.net/pages/scripts/"+settings.apiKey+".js?"+Math.floor(new Date().getTime()/3600000);
a.async=true;a.type="text/javascript";b.parentNode.insertBefore(a,b);
})();
}
},
// Olark
// -----
// _Last updated: October 11th, 2012_
//
// [Documentation](http://www.olark.com/documentation).
'Olark' : {
// Changes to the Olark snippet:
//
// * Removed `CDATA` tags.
// * Add `siteId` from stored `settings`.
// * Added `window.` before `olark.identify`.
initialize : function (settings) {
this.settings = settings = resolveSettings(settings, 'siteId');
window.olark||(function(c){var f=window,d=document,l=f.location.protocol=="https:"?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while(q--){(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={0:+new Date};a.P=function(u){a.p[u]=new Date-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return["<",hd,"></",hd,"><",i,' onl' + 'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{b.contentWindow[g].open()}catch(w){c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{var t=b.contentWindow[g];t.write(p());t.close()}catch(x){b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()})({loader: "static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]});
window.olark.identify(settings.siteId);
},
identify : function (userId, traits) {
if (!userId) return;
window.olark('api.chat.updateVisitorNickname', {
snippet : userId
});
},
track : function (event, properties) {
if (!this.settings.track) return;
window.olark('api.chat.sendNotificationToOperator', {
body : 'Visitor triggered "'+event+'".'
});
}
},
// Chartbeat
// ---------
// _Last updated: November 27th, 2012_
//
// [Documentation](http://chartbeat.com/docs/adding_the_code/),
// [documentation](http://chartbeat.com/docs/configuration_variables/),
// [documentation](http://chartbeat.com/docs/handling_virtual_page_changes/).
'Chartbeat' : {
// Changes to the Chartbeat snippet:
//
// * Add `apiKey` and `domain` variables to config.
// * Added conditionals for extra settings.
// * Replaced the date with our stored `date` variable.
// * Dealt with reliance on window.onload, so that Chartbeat can be
// initialized after the page has loaded.
//
// Also, we don't need to set the `mixpanel` object on `window` because
// they already do that.
initialize : function (settings) {
this.settings = settings = resolveSettings(settings, 'uid');
var _sf_async_config={};
/** CONFIGURATION START **/
_sf_async_config.uid = settings.uid;
_sf_async_config.domain = settings.domain || window.location.host;
if (settings.path) _sf_async_config.path = settings.path;
if (settings.title) _sf_async_config.title = settings.title;
if (settings.useCanonical) _sf_async_config.useCanonical = settings.useCanonical;
if (settings.sections) _sf_async_config.sections = settings.sections;
if (settings.authors) _sf_async_config.authors = settings.authors;
if (settings.noCookies) _sf_async_config.noCookies = settings.noCookies;
/** CONFIGURATION END **/
(function(){
window._sf_endpt = date.getTime();
var e = document.createElement("script");
e.setAttribute("language", "javascript");
e.setAttribute("type", "text/javascript");
e.setAttribute("src",
(("https:" == document.location.protocol) ?
"https://a248.e.akamai.net/chartbeat.download.akamai.com/102508/" :
"http://static.chartbeat.com/") +
"js/chartbeat.js");
document.body.appendChild(e);
})();
}
// TODO: Add virtual page API.
}
};
}).call(this);