-
Notifications
You must be signed in to change notification settings - Fork 1
/
sitehound.js
1708 lines (1536 loc) · 69.5 KB
/
sitehound.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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// SiteHound - Easy & powerful website analytics tracking
//
// Supports tracking events to:
// - Segment.com's analytics.js
// - mixpanel.js
//
// Docs: http://www.sitehound.co
// Source: https://github.com/andyyoung/sitehound
//
// @author Andy Young // @andyy // [email protected]
// @version 0.9.76 - 2nd Dec 2016
// @licence GNU GPL v3
//
// Copyright (C) 2016 Andy Young // [email protected]
// ~~ 500 Startups Distro Team // #500STRONG // 500.co ~~
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
!function() {
var VERSION = "0.9.76",
CONSOLE_PREFIX = '[SiteHound] ',
ALIAS_WAIT_TIMEOUT = 600; // milliseconds
// where we store registered adaptors for different platforms
var adaptors = {};
// kickoff
function init() {
var initialConfig = window.sitehound = window.sitehound || [];
var adaptor = getAdaptor(initialConfig.adaptor);
if (!adaptor) {
// error
return;
}
// initialize SiteHound when our adaptor's target library is ready
if (!initialConfig.silent) {
log('Waiting for the ' + adaptor.klass + ' adaptor to load..');
}
adaptor.ready(function() {
// grab our custom config and calls, if any
var initialConfig = window.sitehound || [];
// initialize SiteHound library, passing in our custom config
var sitehound = new SiteHound(initialConfig, adaptor);
});
}
function SiteHound(initialConfig, adaptor) {
var self = this;
// for auto-detection of page URL change (single-page sites e.g. angularjs)
var intervalId,
currentURL,
urlChangeQueue = [];
// store for deferred adaptor functions
var adaptorDeferredFunctions,
adaptorDeferredQueue = [];
// maintain list of Optimizely Experiment IDs we've detected
var optimizelyActiveExperimentsDetected = [],
optimizelyIntervalId;
if (initialConfig.adaptor && ((initialConfig.adaptor.klass || initialConfig.adaptor) !== adaptor.klass)) {
// adaptor has been changed since initial load
setAdaptor(getAdaptor(initialConfig.adaptor));
} else {
setAdaptor(adaptor);
}
if (typeof this.adaptor !== 'object') {
error('adaptor not valid');
return;
}
// wrapper for initialization
!function() {
var config = {
// object mapping names to match patterns for key pages we want to track
// - by default we match against the page URL (location.pathname)
// - strings beginning with a '.' match css classes on the <body>
// match patterns can be simple strings, arrays, or regular expressions
trackPages: null,
// override detection of the current page (and therefore track this pageview event)
page: null,
// track all other pageviews not covered above? (as "unidentified")
trackAllPages: false,
// detect and track new pageview events if the window.location changes?
detectURLChange: true,
detectHashChange: false,
// disable tracking on particular hosts
domainsIgnore: ['localhost', 'gtm-msr.appspot.com'],
domainsIgnoreIPAddress: true,
domainsIgnoreSubdomains: ['staging', 'test'],
// disable tracking from particular IP addresses
// supports * wildcard and prefix match e.g. 'w.*.y.' matches 'w.x.y.z'
ignoreIPs: [],
// add traits for visitors from particular IP addresses
// accepts array of objects with two keys: ip (string or array, wildcard + prefix matches as above), and traits (object)
addTraitsForIPs: [], // [{ip: 'w.x.y.z', traits: {a:'b', ..}}, {ip: ['w.x.y.z', ..], traits: {..}}, ..]
// if we have any landing pages without this tracking installed, list them here
// in order to track them as the "true" landing page when the user clicks through to
// a page with tracking
trackReferrerLandingPages: [],
// traits to set globally for this user/session
globalTraits: {},
// traits to set only on any page event we may trigger during this pageview
pageTraits: {},
// traits to set on all events during this pageview, but not set globally for subsequent pageviews
thisPageTraits: {},
// do we have an ID for a logged-in user?
userId: undefined,
// traits to set on the user (like globalTraits, but will be prefixed with "User " to distinguish them)
userTraits: {},
// should we fire a logout event on this page if we don't have a userId set but were previously logged in?
// - defaults to true if we've passed a value (incl. null), false otherwise
detectLogout: undefined,
// suppress all non-error output to the console?
silent: false,
// session timeout before tracking the start of a new session (in minutes)
sessionTimeout: 30,
// provide an overridden referrer to replce in when tracking on this page
overrideReferrer: undefined,
// queued-up methods to execute
queue: [],
// locally-persisted client context - stored urlencoded via cookie
clientContext: {},
// ..stored only for the session duration
clientSessionContext: {},
// preserve from snippet to assist with debugging
SNIPPET_VERSION: undefined
};
self.sniffed = false;
// process array-style queue
for (var key in config) {
if (initialConfig[key] !== undefined) {
config[key] = initialConfig[key];
}
self[key] = config[key];
}
while (initialConfig.length && initialConfig.pop) {
// window.sitehound quacks like an array
// prepend each method call to the queue
self.queue.unshift(initialConfig.pop());
}
self.thisPageTraits['SiteHound library version'] = self.VERSION = VERSION;
}();
// final initialization steps
function completeInit() {
self.info('Loaded (version ' + VERSION + ', adaptor: ' + self.adaptor.klass + ')');
self.cookieDomain = topDomain(location.hostname);
self.debug('Cookie domain: ' + self.cookieDomain);
// populate from cookie
readLocalContext();
if (self.clientContext.dnt) {
self.info('Do-not-track cookie present - disabling.');
self.disable();
}
// replace the global sitehound var with our instance
window.sitehound = self;
if (window.mixpanel && window.mixpanel.persistence && document.cookie.indexOf(window.mixpanel.persistence.name + '=') > -1) {
// detected Mixpanel cookie - warn to switch to localstorage
error('Warning: Mixpanel cookie detected - update Mixpanel config to use localStorage.');
}
// replay any ready()/identify() events queued up by the snippet before the lib was loaded
replayPreSniff();
if (initialConfig.sniffOnLoad || initialConfig.isDone) { // isDone: legacy
self.sniff();
}
}
//
// privileged methods
//
this.sniff = this.done = function() { // done(): legacy name
try {
self.info('sniff()');
// check we want to track this host
if (ignoreHost(location.hostname)) {
self.info('Ignoring host: ' + location.hostname);
self.disable();
}
if (self.clientContext.dnt) {
self.info('Do-not-track cookie present - disabling.');
self.disble();
}
if (self.ignoreIPs || self.addTraitsForIPs) {
// if not yet known, will lookup asynchronously in time for the next pageview
getClientIP();
if (ignoreIP()) {
self.info('Ignoring IP: ' + self.clientContext.ip + '; matched pattern: ' + (self.ignoreIPs.join ? self.ignoreIPs.join(',') : self.ignoreIPs));
self.disable();
}
addTraitsForIP();
}
var firstSniff = !self.sniffed;
// core tracking for on page load
doSniff();
// beyond this point should only be executed once per pageview
if (!firstSniff) {
return;
}
// replay any remaining events queued up by the snippet before the lib was loaded
// or calls since the lib was loaded but queued for post-sniffing
replayQueue();
// auto-detect URL change and re-trigger sniffing for any future virtual pageviews
if ((self.detectURLChange || self.detectHashChange) && !intervalId) {
currentURL = location.href;
intervalId = setInterval(
function() {
if (self.detectHashChange ?
(location.href !== currentURL) :
(location.href.replace(/#.*$/, '') !== currentURL.replace(/#.*$/, ''))
) {
urlChanged(currentURL);
currentURL = location.href;
}
},
1000
);
}
} catch (e) {
this.trackError(e);
}
}
this.deferUntilSniff = function(method, args) {
if (self.sniffed) {
// already sniffed - no need to defer
return false;
} // else - defer until we've sniffed
// convert from Arguments type to real array
args = Array.prototype.slice.call(args);
args.unshift(method);
self.queue.push(args);
self.debug('(Deferring ' + method + '() until sniff)');
return true;
}
this.identify = function(a, b) {
self.debug('identify', [a, b]);
if (typeof b === 'object') {
// (id, traits)
self.userId = a;
self.globalTraits = mergeObjects(self.globalTraits, b);
} else if (typeof a === 'object') {
// (traits)
self.globalTraits = mergeObjects(self.globalTraits, a);
} else {
// (id)
self.userId = a;
}
if (self.sniffed) {
// already sniffed - call adaptor.identify()
doIdentify();
} // else - adaptor.identify() will be called when we sniff()
}
// like analytics.identify({..}), but only set traits if they're not already set
this.identifyOnce = function(params) {
if (self.deferUntilSniff('identifyOnce', arguments)) {return;}
self.debug('identifyOnce', params);
self.adaptor.identifyOnce(params);
}
this.detectPage = function(path) {
if (path === undefined) {
path = location.pathname;
if (self.page) {
self.debug('Page manually set to: ' + self.page);
return self.page;
}
}
for (var page in self.trackPages) {
var pattern = self.trackPages[page];
// we support matching based on string, array or regex
if (!Array.isArray(pattern)) {
pattern = [pattern];
}
for (var i = 0; i < pattern.length; ++i) {
var pat = pattern[i];
if (typeof pat.test === 'function') {
if (pat.test(path)) {
// regex matching URL path - TOCHECK
self.debug('Detected page: ' + page);
return page;
}
} else if (pat[0] === '.') {
// match body css class
if ((path === location.pathname) &&
document.body.className.match(new RegExp('(?:^|\\s)' + escapeRegExp(pat.slice(1)) + '(?!\\S)'))) {
self.debug('Detected page: ' + page);
return page;
}
} else {
// string match - match whole path
// we ignore presence of trailing slash on path
// treat * as a wildcard
if (path.replace(/\/$/, '').match(new RegExp('^' + escapeRegExp(pat.replace(/\/$/, '')).replace(/\\\*/g, '.*') + '$'))) {
self.debug('Detected page: ' + page);
return page;
}
}
}
}
}
this.getTraitsToSend = function(traits) {
var otherTraits = mergeObjects(self.globalTraits, self.thisPageTraits);
if (typeof traits === 'object') {
return mergeObjects(otherTraits, traits);
} else {
return otherTraits;
}
}
this.info = function(message, object) {
if (self.silent) {
return;
}
log(message, object);
}
this.debug = function(message, object) {
// alias debug() / debug(false) to debugMode(true/false)
if (object === undefined) {
if (message === undefined) {
return self.debugMode();
} else if (message === false) {
return self.debugMode(false);
}
}
if (!self.clientContext.logToConsole) {
return;
}
log(message, object);
}
this.doNotTrack = function(dnt) {
dnt = (typeof dnt === 'undefined') ? true : !!dnt;
setLocalContext('dnt', dnt);
self.debug('doNotTrack:' + dnt);
}
this.debugMode = function(logToConsole) {
logToConsole = (typeof logToConsole === 'undefined') ? true : !!logToConsole;
setLocalContext('logToConsole', logToConsole);
self.debug('debugMode: ' + logToConsole);
}
this.onURLChange = this.onUrlChange = function(f) {
if (typeof f === 'function') {
this.debug('onURLChange()');
urlChangeQueue.push(f);
} else {
error("onURLChange() called with something that isn't a function");
}
}
this.load = function(adaptor) {
self.debug('load() called when already loaded');
if (adaptor) {
setAdaptor(getAdaptor(adaptor));
self.info('Updated adaptor to: ' + self.adaptor.klass);
}
}
this.disable = function() {
setAdaptor(getAdaptor('disabled'));
self.info('Disabled tracking');
}
//
// private methods
//
function ignoreHost(host) {
if (self.domainsIgnore.indexOf(host) != -1) {
// domain is one we've specifically listed to ignore
return true;
}
if (self.domainsIgnoreIPAddress && /([0-9]{1,3}\.){3}[0-9]{1,3}/.test(host)) {
// host is IP address, and we want to ignore these
return true;
}
for (var i = 0; i < self.domainsIgnoreSubdomains.length; i++) {
if (host.indexOf(self.domainsIgnoreSubdomains[i] + '.') == 0) {
// host matches a subdomain pattern we wish to ignore
return true;
}
}
// else
return false;
}
function getClientIP() {
// refresh client IP every 30 minutes
if (!self.clientContext.ip
|| !self.clientContext.ipLookupTime
|| ((new Date().getTime() - self.clientContext.ipLookupTime) > 1800000)) {
// make call to ipify.com to get the client IP address
self.debug('looking up ip');
var jsonpCallbackHash = Math.random().toString(36).substring(2,12);
self['setIP_' + jsonpCallbackHash] = function(ip) {
self.debug('received IP: ', ip);
if (!ip || !ip.ip) { return; }
setLocalContext('ip', ip.ip);
setLocalContext('ipLookupTime', new Date().getTime());
};
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = 'https://api.ipify.org?format=jsonp&callback=sitehound.setIP_' + jsonpCallbackHash;
var first = document.getElementsByTagName('script')[0];
first.parentNode.insertBefore(script, first);
}
return self.clientContext.ip;
}
function ignoreIP() {
if (!self.clientContext.ip || !self.ignoreIPs || !self.ignoreIPs.length) {
return;
}
console.log(getIPRegExp(self.ignoreIPs));
return getIPRegExp(self.ignoreIPs).test(self.clientContext.ip);
}
function addTraitsForIP() {
if (!self.addTraitsForIPs || !self.addTraitsForIPs.map) { return; }
self.addTraitsForIPs.map(function(rule) {
if (rule && rule.ip && rule.traits) {
if (getIPRegExp(rule.ip).test(self.clientContext.ip)) {
self.debug('Matched IP rule: ' + rule.ip, rule.traits);
self.globalTraits = mergeObjects(self.globalTraits, rule.traits);
}
} else {
console.debug('Invalid addTraitsForIP rule', rule);
}
});
}
function getIPRegExp(ip) {
if (ip && ip.map) {
return new RegExp('^(' + ip.map(function(i) { return getIPRegExp(i).toString().replace(/[\/\^\$]/g, ''); })
.join('|') + ')$');
}
return new RegExp('^' + ip.replace(/\./g, '\\.').replace(/\.$/, '.*').replace('*', '.+') + '$');
}
function doSniff() {
// set this now so our tracking calls execute immediately without deferUntilSniff()
self.sniffed = true;
if (!self.page) {
self.page = self.detectPage();
}
self.thisPageTraits['Page Type'] = self.page;
// cleanify
if (self.userId === 'undefined') {
self.userId = undefined;
}
// collect data related to the current session
examineSession();
// some user-related properties
var userTraits = self.adaptor.userTraits();
if (userTraits.createdAt) {
self.globalTraits['Days Since Signup'] = Math.floor((new Date()-new Date(userTraits.createdAt))/1000/60/60/24);
self.debug('Days since signup: ' + self.globalTraits['Days Since Signup']);
}
if (self.userTraits['Email Domain']) {
self.userTraits['Email Domain'] = self.userTraits['Email Domain'].match(/[^@]*$/)[0];
} else if (userTraits.Email || userTraits.email || self.userTraits['Email']) {
self.userTraits['Email Domain'] = (userTraits.Email || userTraits.email || self.userTraits['Email']).match(/[^@]*$/)[0];
}
// Fullstory.com session URL
if (window.FS && window.FS.getCurrentSessionURL) {
// ideally do it instantly so we don't trigger a separate identify() call
self.globalTraits['Fullstory URL'] = FS.getCurrentSessionURL() || '';
} else if (!self.sniffed) {
var _old_fs_ready = window._fs_ready;
window._fs_ready = function() {
self.adaptor.identify({'Fullstory URL': FS.getCurrentSessionURL() || ''});
if (typeof _old_fs_ready === 'function') {
_old_fs_ready();
}
};
}
// Optimizely
var optimizelyEvents = detectOptimizelyExperiments(userTraits);
if (self.overrideReferrer !== undefined) {
self.thisPageTraits['referrer'] = self.thisPageTraits['Referrer'] = self.thisPageTraits['$referrer'] = self.overrideReferrer;
}
// handle user identification, including login/logout
doIdentify();
// track session started event?
if (self.trackSessionStart) {
self.track('Session Started');
// only do this once
self.trackSessionStart = false;
}
// track landing page event?
if (self.trackLandingPage) {
self.track('Viewed Landing Page', self.landingPageTraits);
// only do this once
self.trackLandingPage = false;
}
// track page view event?
if (self.page) {
// if the page contains a vertical bar, separate out the page vs. category
var pageParts = self.page.split('|', 2).map(
function(a) {
return a.trim();
}
);
var args = pageParts.push(self.pageTraits);
trackPage.apply(self, pageParts);
} else if (self.trackAllPages) {
trackPage('Unidentified');
}
// track Optimizely experiment views after we've handled user identification and page tracking
trackOptimizelyEvents(optimizelyEvents);
// poll for newly activted Optimizely experiments
if (!optimizelyIntervalId && window.optimizely && window.optimizely.data) {
optimizelyIntervalId = setInterval(
function() { trackOptimizelyEvents(detectOptimizelyExperiments()); },
300
);
}
}
function examineSession() {
// visitor first seen
var firstSeen = self.clientContext.firstSeen || new Date().toISOString();
setLocalContext('firstSeen', firstSeen);
var daysSinceFirst = Math.floor((new Date() - new Date(firstSeen))/1000/60/60/24);
self.globalTraits['First Seen'] = firstSeen;
self.globalTraits['Days Since First Seen'] = daysSinceFirst;
self.debug('Visitor first seen: ' + firstSeen);
self.debug('Days since first seen: ' + daysSinceFirst);
// session start + last updated time
var sessionStarted = self.clientSessionContext.sessionStarted || new Date().toISOString(),
sessionUpdated = self.clientSessionContext.sessionUpdated || new Date().toISOString();
var sessionSilent = Math.floor((new Date() - new Date(sessionUpdated))/1000/60);
self.debug('Session started: ' + sessionStarted);
self.debug('Minutes since last event: ' + sessionSilent);
var sessionTimedOut = sessionSilent > self.sessionTimeout;
if (sessionTimedOut) {
self.debug('Session timed out - tracking as new session');
sessionStarted = new Date().toISOString();
}
var sessionDuration = Math.floor((new Date() - new Date(sessionStarted))/1000/60);
self.debug('Session duration: ' + sessionDuration);
self.globalTraits['Session Started'] = sessionStarted;
self.globalTraits['Minutes Since Session Start'] = sessionDuration;
setLocalContext('sessionStarted', sessionStarted, true);
setLocalContext('sessionUpdated', new Date().toISOString(), true);
// tracked pageviews this session
var pageViews = (sessionTimedOut ? 0 : parseInt(self.clientSessionContext.pageViews || 0)) + 1;
self.thisPageTraits['Pageviews This Session'] = pageViews;
setLocalContext('pageViews', pageViews, true);
self.debug('Pageviews: ' + pageViews);
var referrerParts = document.referrer.match(/https?:\/\/([^/]+)(\/.*)/),
referrerHost = null,
referrerPath;
if (referrerParts) {
referrerHost = referrerParts[1];
referrerPath = referrerParts[2];
}
if (referrerHost == location.host) {
self.thisPageTraits['Referrer Type'] = self.detectPage(referrerPath);
}
self.thisPageTraits['Host'] = location.host;
if (!sessionTimedOut) {
// is this a landing page hit? (i.e. first pageview in session)
if (pageViews > 1) {
// not a landing page - nothing further to do here
return;
}
self.debug('Detected landing page');
}
// session count for this visitor
var sessionCount = parseInt(self.clientContext.sessionCount || 0) + 1;
self.globalTraits['Session Count'] = sessionCount;
setLocalContext('sessionCount', sessionCount);
self.debug('Session count: ' + sessionCount);
// at this point we're either a landing page hit or counting a new session due to timeout
// track Session Started event for identified users and session timeouts
// i.e. not anonymous landing pages, of which we typically expect many
// but already have the Landing Page event for.
self.trackSessionStart = sessionTimedOut || self.userId;
if (sessionTimedOut) {
// we don't update attribution tracking when tracking a new session due to inactivity
return;
}
// track attribution params for this session
var attributionParams = {};
var paramNames = [
'UTM Source',
'UTM Medium',
'UTM Campaign',
'UTM Term',
'UTM Content',
'Landing Page',
'Landing Page Type',
'Initial Referrer',
'Initial Referring Domain'
];
for (var i = 0; i < paramNames.length; i++) {
attributionParams[paramNames[i]] = '';
}
// utm params
var utmParams = getUTMParams();
if (Object.keys(utmParams).length > 0) {
self.debug('utm params:');
self.debug(utmParams);
attributionParams = mergeObjects(attributionParams, utmParams);
}
// Landing page
//
// This is the first page on which we've tracked this user, so if the referrer is from the same domain,
// then the referring page (likely the original landing page?) didn't have our tracking code implemented
if (referrerHost === location.host) {
// Did we specify to track this particular referrer as the original landing page?
if (self.trackReferrerLandingPages.indexOf(referrerPath) !== -1) {
self.debug('Detected known untracked landing page: ' + document.referrer);
self.trackLandingPage = true;
self.landingPageTraits = {
path: referrerPath,
url: document.referrer,
'$current_url': document.referrer,
'Tracked From URL': location.href,
referrer: ''
};
attributionParams['Landing Page'] = referrerPath;
} else if (document.referrer === location.href) {
// referrer is the current page - treat as landing page
self.trackLandingPage = true;
attributionParams['Landing Page'] = location.pathname;
} else if (sessionCount > 1) {
// not the first session - mostly likely page reload triggered with referrer but no session cookie
// due to reopening a previously-closed mobile browser
// - ignore
} else {
self.trackDebugWarn('Landing page with local referrer - tracking code not on all pages?');
}
} else {
self.trackLandingPage = true;
attributionParams['Landing Page'] = location.pathname;
attributionParams['Initial Referrer'] = document.referrer ? document.referrer : '';
attributionParams['Initial Referring Domain'] = referrerHost;
}
// add some additional metadata
if (attributionParams['Landing Page']) {
attributionParams['Landing Page Type'] = self.page;
}
// automatic attribution detection
if (!attributionParams['UTM Source']) {
// adwords / doubleclick
if (getQueryParam(document.URL, 'gclid') || getQueryParam(document.URL, 'gclsrc')) {
attributionParams['UTM Source'] = 'google';
if (!attributionParams['UTM Medium']) {
attributionParams['UTM Medium'] = 'cpc';
}
}
// Yesware
if (attributionParams['Referring Domain'] == 't.yesware.com') {
attributionParams['UTM Source'] = 'Yesware';
if (!attributionParams['UTM Medium']) {
attributionParams['UTM Medium'] = 'email';
}
}
}
var attributionParamsFirst = {},
attributionParamsLast = {};
for (var key in attributionParams) {
attributionParamsFirst[key + ' [first touch]'] = attributionParams[key];
attributionParamsLast[key + ' [last touch]'] = attributionParams[key];
}
self.debug('Attribution params:');
self.debug(attributionParams);
if ((sessionCount == 1) && (self.thisPageTraits['Pageviews This Session'] == 1)) {
// only track first touch params on first session
self.debug('..setting first touch params');
self.globalTraits = mergeObjects(self.globalTraits, attributionParamsFirst);
}
self.debug('..setting last touch params');
self.globalTraits = mergeObjects(self.globalTraits, attributionParamsLast);
}
function detectOptimizelyExperiments(userTraits) {
var result = [];
var optimizely = window.optimizely;
if (!optimizely || !optimizely.data) {
return result;
}
var oData = optimizely.data;
var oState = oData.state,
oSections = oData.sections;
var activeExperiments = oState.activeExperiments;
if(oState.redirectExperiment) {
var redirectExperimentId = oState.redirectExperiment.experimentId;
var index = oState.activeExperiments.indexOf(redirectExperimentId);
if (index === -1) {
activeExperiments.push(redirectExperimentId);
self.overrideReferrer = oState.redirectExperiment.referrer;
}
}
if (!activeExperiments.length) {
// return empty result
return result;
}
if (userTraits === undefined) {
userTraits = self.adaptor.userTraits();
}
var oEsKey = 'Optimizely Experiments',
oVsKey = 'Optimizely Variations',
activeExperimentsKey = 'Optimizely Experiments Active',
activeVariantsKey = 'Optimizely Variations Active';
var oEs = userTraits[oEsKey],
oVs = userTraits[oVsKey],
activeEs = self.thisPageTraits[activeExperimentsKey] = self.thisPageTraits[activeExperimentsKey] || [],
activeVs = self.thisPageTraits[activeVariantsKey] = self.thisPageTraits[activeVariantsKey] || [];
self.globalTraits[oEsKey] = oEs ? (typeof oEs.sort === 'function' ? oEs : [oEs]) : [];
self.globalTraits[oVsKey] = oVs ? (typeof oVs.sort === 'function' ? oVs : [oVs]) : [];
for (var i = 0; i < activeExperiments.length; i++) {
var experimentId = activeExperiments[i];
if (optimizelyActiveExperimentsDetected.indexOf(experimentId) > -1) {
// already tracked this active experiment
continue;
}
optimizelyActiveExperimentsDetected.push(experimentId);
var variationId = oState.variationIdsMap[experimentId][0].toString();
var experimentTraits = {
'Experiment ID': experimentId,
'Experiment Name': oData.experiments[experimentId].name,
'Experiment First View': !oEs || !oEs.indexOf || (oEs.indexOf(experimentId) === -1),
'Variation ID': variationId,
'Variation Name': oState.variationNamesMap[experimentId]
};
if (self.globalTraits[oEsKey].indexOf(experimentId) === -1) {
self.globalTraits[oEsKey].push(experimentId);
}
if (activeEs.indexOf(experimentId) === -1) {
activeEs.push(experimentId);
}
var multiVariate = oSections[experimentId];
if (multiVariate) {
experimentTraits['Section Name'] = multiVariate.name;
experimentTraits['Variation ID'] = multiVariate.variation_ids.join();
for (var v = 0; v < multiVariate.variation_ids.length; v++) {
if (self.globalTraits[oVsKey].indexOf(multiVariate.variation_ids[v]) === -1) {
self.globalTraits[oVsKey].push(multiVariate.variation_ids[v]);
}
if (activeVs.indexOf(multiVariate.variation_ids[v]) === -1) {
activeVs.push(multiVariate.variation_ids[v]);
}
}
} else {
if (self.globalTraits[oVsKey].indexOf(variationId) === -1) {
self.globalTraits[oVsKey].push(variationId);
}
if (activeVs.indexOf(variationId) === -1) {
activeVs.push(variationId);
}
}
result.push(['Optimizely Experiment Viewed', experimentTraits]);
}
if (result.length) {
self.globalTraits[oEsKey].sort();
self.globalTraits[oVsKey].sort();
activeEs.sort();
activeVs.sort();
}
return result;
}
function trackOptimizelyEvents(events) {
for (var i = 0; i < events.length; i++) {
self.track(events[i][0], events[i][1]);
}
}
// handle user identification, including login/logout
function doIdentify() {
// to be explicit
var mixpanel = window.mixpanel;
var amplitude = window.amplitude;
if (self.userId) {
// we have a logged-in user
self.debug('doIdentify(): received userId: ' + self.userId);
var userTraits = {},
specialKeys = [
'name',
'firstName',
'lastName',
'email',
'createdAt'
];
for (var key in self.userTraits) {
// TODO: support for all segment/mixpanel special traits, and camel/snake case a la segment
// get the traits from the adaptor?
var keyLower = key.toLowerCase(),
newKey = '';
for (var i = 0; i < specialKeys.length; i++) {
if (keyLower === specialKeys[i].toLowerCase()) {
newKey = specialKeys[i];
break;
}
}
if (!newKey) {
newKey = 'User ' + titleCase(key);
}
userTraits[newKey] = self.userTraits[key];
}
var traits = mergeObjects(self.globalTraits, userTraits);
var currentUserId;
if (!self.adaptor.userId()) {
self.debug('Anonymous session until now');
// ~~ Mixpanel hack ~~
// At this point we alias() for Mixpanel
// (alias() is not implemented with most other tools - e.g. Amplitude aliases anon => logged in users by default)
//
// For Mixpanel, we consciously go against their recommendation and always alias() on login
// If a profile with this user ID already exists within Mixpanel, it will ignore the alias() call
//
// Below, we subsequently ensure identify() takes hold even if alias() was silently ignored because already in use
//
// First, alias() for Segment - will be passed through to data warehouse etc
if (usingSegment()) {
self.debug('analytics.alias(' + self.userId + ')');
self.adaptor.alias(self.userId,
undefined,
{integrations: {'Mixpanel': false}}
);
}
// handle Mixpanel specially
if (usingMixpanel()) {
// recreate mixpanel.alias() but with our own behaviours
var current = mixpanel.get_distinct_id ? mixpanel.get_distinct_id() : null;
if (current != self.userId) {
self.debug('Mixpanel: $create_alias');
// pause future identify() and track() calls until the alias() callback has completed
pauseAdaptor();
mixpanel.register({ '__alias': self.userId });
mixpanel.track('$create_alias', { 'alias': self.userId, 'distinct_id': current }, function() {
// callback - mixpanel alias API call complete
// unlike mixpanel.js, we don't call identify() here (to flush the people queue)
// since we're calling it shortly anyhow
//
// resume paused calls
self.debug('Mixpanel: $create_alias callback');
resumeAdaptor();
});
// unpause within 300ms regardless
setTimeout(function() {
self.debug('Mixpanel: ALIAS_WAIT_TIMEOUT reached');
resumeAdaptor();
}, ALIAS_WAIT_TIMEOUT);
} else {
self.debug('mixpanel.distinct_id == sitehound.userId; no Mixpanel alias call');
}
}
} else {
// We previously had a userId
currentUserId = self.adaptor.userId();
self.debug('Current userId: ' + currentUserId);
if (self.userId !== currentUserId) {
// User ID mismatch - we need to log out
var amp;
if (usingAmplitude() && amplitude.getInstance && (amp = amplitude.getInstance())) {
self.debug('Amplitude: logout');
// Amplitude logout: https://github.com/amplitude/Amplitude-Javascript/#logging-out-and-anonymous-users
// Force log out so Amplitude doesn't combine user profiles as by default
amp.setUserId(null);
// Amplitude uses it's Device ID to track users, and to implement a log out requires
// us to explicitly create a new Device ID
if (amp.regenerateDeviceId) {
amp.regenerateDeviceId();
}
}
// else if not using Amplitude - no need to log out
// instead we overwrite with new userId via the calls below
// NB if this is a first-time login for the new userID, this will legitimately create a new
// profile with distinct_id as the new ID, rather than a UUID
}
}
self.debug('adaptor.identify(' + self.userId + ', [traits])');
self.adaptor.identify(self.userId, traits);
if (usingMixpanel()) {
// Mixpanel fix: ensure we set mixpanel.distinct_id - and thus send all subsequent events with
// the new userId - even if self.userId == mixpanel.ALIAS_ID_KEY
// Since by default the Mixpanel library will stick with sending events under the old ID
// when we've just aliased to the new ID. Therefore, if we called alias for an ID that had
// already been aliased, subsequent events would end up under the incorrect user ID.
// The fact we're doing this is why we need to delay all subsequent events until the callback
// for the prior alias call indicates it was received successfully.
self.debug('Mixpanel: set distinct_id');
mixpanel.register({ distinct_id: self.userId });
}
if ((self.userId !== currentUserId) || self.clientSessionContext.loggedOut) {
self.debug('userId != currentUserId - Login');
self.track('Login');
setLocalContext('loggedOut', '', true);
}
} else {
// no information about whether the user is currently logged in
// Nb: calling analytics.identify() without a userId will delegate to identify() with the user.id() from analytics.js
self.adaptor.identify(self.globalTraits);
if (self.adaptor.userId()) {
if (usingMixpanel()) {
// Mixpanel fix: ensure we set mixpanel.distinct_id in sync with userId - as above
self.debug('Mixpanel: register({distinct_id: ' + self.adaptor.userId() + '})')
mixpanel.register({ distinct_id: self.adaptor.userId() });
}
if (self.thisPageTraits['Pageviews This Session'] == 1) {
// not told we're logged in, but we have a user ID from the analytics persistence, and
// it's our first pageview this session - therefore we were logged in and then out in prior session(s)
// - set logged_out session cookie to prevent tracking a false logout event at the start of this session
self.debug('not logged in, but user ID from prior session - setting logged_out cookie');
setLocalContext('loggedOut', true, true);
}
}
// by default, automatically detect logout if the userId property has been set
// - even if it's been set to null
self.detectLogout = (self.detectLogout === undefined) ? (self.userId !== undefined) : self.detectLogout;
if (self.detectLogout && !self.clientSessionContext.loggedOut) {
// we don't actually "log out" for the anaytics - keep tracking under the same user ID