forked from snowplow/snowplow-javascript-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracker.js
More file actions
executable file
·2504 lines (2223 loc) · 79.5 KB
/
Copy pathtracker.js
File metadata and controls
executable file
·2504 lines (2223 loc) · 79.5 KB
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
/*
* JavaScript tracker for Snowplow: tracker.js
*
* Significant portions copyright 2010 Anthon Pang. Remainder copyright
* 2012-2016 Snowplow Analytics Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Anthon Pang nor Snowplow Analytics Ltd nor the
* names of their contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
;(function() {
var
lodash = require('./lib_managed/lodash'),
helpers = require('./lib/helpers'),
proxies = require('./lib/proxies'),
cookie = require('browser-cookie-lite'),
detectors = require('./lib/detectors'),
sha1 = require('sha1'),
links = require('./links'),
forms = require('./forms'),
errors = require('./errors'),
requestQueue = require('./out_queue'),
coreConstructor = require('snowplow-tracker-core').trackerCore,
uuid = require('uuid'),
object = typeof exports !== 'undefined' ? exports : this; // For eventual node.js environment support
/**
* Snowplow Tracker class
*
* @param functionName global function name
* @param namespace The namespace of the tracker object
* @param version The current version of the JavaScript Tracker
* @param mutSnowplowState An object containing hasLoaded, registeredOnLoadHandlers, and expireDateTime
* Passed in by reference in case they are altered by snowplow.js
* @param argmap Optional dictionary of configuration options. Supported fields and their default values:
*
* 1. encodeBase64, true
* 2. cookieDomain, null
* 3. cookieName, '_sp_'
* 4. appId, ''
* 5. platform, 'web'
* 6. respectDoNotTrack, false
* 7. userFingerprint, true
* 8. userFingerprintSeed, 123412414
* 9. pageUnloadTimer, 500
* 10. forceSecureTracker, false
* 11. forceUnsecureTracker, false
* 12. useLocalStorage, true
* 13. useCookies, true
* 14. sessionCookieTimeout, 1800
* 15. contexts, {}
* 16. post, false
* 17. bufferSize, 1
* 18. crossDomainLinker, false
* 19. maxPostBytes, 40000
* 20. discoverRootDomain, false
* 21. cookieLifetime, 63072000
* 22. stateStorageStrategy, 'cookieAndLocalStorage'
* 23. respectOptOutCookie, false
*/
object.Tracker = function Tracker(functionName, namespace, version, mutSnowplowState, argmap) {
/************************************************************
* Private members
************************************************************/
var
// Tracker core
core = coreConstructor(true, function(payload) {
addBrowserData(payload);
sendRequest(payload, configTrackerPause);
}),
// Aliases
documentAlias = document,
windowAlias = window,
navigatorAlias = navigator,
// Current URL and Referrer URL
locationArray = proxies.fixupUrl(documentAlias.domain, windowAlias.location.href, helpers.getReferrer()),
domainAlias = helpers.fixupDomain(locationArray[0]),
locationHrefAlias = locationArray[1],
configReferrerUrl = locationArray[2],
// Holder of the logPagePing interval
pagePingInterval,
customReferrer,
argmap = argmap || {},
// Request method is always GET for Snowplow
configRequestMethod = 'GET',
// Platform defaults to web for this tracker
configPlatform = argmap.hasOwnProperty('platform') ? argmap.platform : 'web',
// Snowplow collector URL
configCollectorUrl,
// Site ID
configTrackerSiteId = argmap.hasOwnProperty('appId') ? argmap.appId : '', // Updated for Snowplow
// Document URL
configCustomUrl,
// Document title
lastDocumentTitle = documentAlias.title,
// Custom title
lastConfigTitle,
// Maximum delay to wait for web bug image to be fetched (in milliseconds)
configTrackerPause = argmap.hasOwnProperty('pageUnloadTimer') ? argmap.pageUnloadTimer : 500,
// Whether appropriate values have been supplied to enableActivityTracking
activityTrackingEnabled = false,
// Minimum visit time after initial page view (in milliseconds)
configMinimumVisitTime,
// Recurring heart beat after initial ping (in milliseconds)
configHeartBeatTimer,
// Disallow hash tags in URL. TODO: Should this be set to true by default?
configDiscardHashTag,
// First-party cookie name prefix
configCookieNamePrefix = argmap.hasOwnProperty('cookieName') ? argmap.cookieName : '_sp_',
// First-party cookie domain
// User agent defaults to origin hostname
configCookieDomain = argmap.hasOwnProperty('cookieDomain') ? argmap.cookieDomain : null,
// First-party cookie path
// Default is user agent defined.
configCookiePath = '/',
// Do Not Track browser feature
dnt = navigatorAlias.doNotTrack || navigatorAlias.msDoNotTrack || windowAlias.doNotTrack,
// Do Not Track
configDoNotTrack = argmap.hasOwnProperty('respectDoNotTrack') ? argmap.respectDoNotTrack && (dnt === 'yes' || dnt === '1') : false,
// Opt out of cookie tracking
configOptOutCookie,
// Count sites which are pre-rendered
configCountPreRendered,
// Life of the visitor cookie (in seconds)
configVisitorCookieTimeout = argmap.hasOwnProperty('cookieLifetime') ? argmap.cookieLifetime : 63072000, // 2 years
// Life of the session cookie (in seconds)
configSessionCookieTimeout = argmap.hasOwnProperty('sessionCookieTimeout') ? argmap.sessionCookieTimeout : 1800, // 30 minutes
// Default hash seed for MurmurHash3 in detectors.detectSignature
configUserFingerprintHashSeed = argmap.hasOwnProperty('userFingerprintSeed') ? argmap.userFingerprintSeed : 123412414,
// Document character set
documentCharset = documentAlias.characterSet || documentAlias.charset,
// This forces the tracker to be HTTPS even if the page is not secure
forceSecureTracker = argmap.hasOwnProperty('forceSecureTracker') ? (argmap.forceSecureTracker === true) : false,
// This forces the tracker to be HTTP even if the page is secure
forceUnsecureTracker = !forceSecureTracker && argmap.hasOwnProperty('forceUnsecureTracker') ? (argmap.forceUnsecureTracker === true) : false,
// Whether to use localStorage to store events between sessions while offline
useLocalStorage = argmap.hasOwnProperty('useLocalStorage') ? (
helpers.warn('argmap.useLocalStorage is deprecated. ' +
'Use argmap.stateStorageStrategy instead.'),
argmap.useLocalStorage
) : true,
// Whether to use cookies
configUseCookies = argmap.hasOwnProperty('useCookies') ? (
helpers.warn(
'argmap.useCookies is deprecated. Use argmap.stateStorageStrategy instead.'),
argmap.useCookies
) : true,
// Strategy defining how to store the state: cookie, localStorage or none
configStateStorageStrategy = argmap.hasOwnProperty('stateStorageStrategy') ?
argmap.stateStorageStrategy : (!configUseCookies && !useLocalStorage ?
'none' : (configUseCookies && useLocalStorage ?
'cookieAndLocalStorage' : (configUseCookies ? 'cookie' : 'localStorage'))),
// Browser language (or Windows language for IE). Imperfect but CloudFront doesn't log the Accept-Language header
browserLanguage = navigatorAlias.userLanguage || navigatorAlias.language,
// Browser features via client-side data collection
browserFeatures = detectors.detectBrowserFeatures(
configStateStorageStrategy == 'cookie' ||
configStateStorageStrategy == 'cookieAndLocalStorage',
getSnowplowCookieName('testcookie')),
// Visitor fingerprint
userFingerprint = (argmap.userFingerprint === false) ? '' : detectors.detectSignature(configUserFingerprintHashSeed),
// Unique ID for the tracker instance used to mark links which are being tracked
trackerId = functionName + '_' + namespace,
// Guard against installing the activity tracker more than once per Tracker instance
activityTrackingInstalled = false,
// Last activity timestamp
lastActivityTime,
// The last time an event was fired on the page - used to invalidate session if cookies are disabled
lastEventTime = new Date().getTime(),
// How are we scrolling?
minXOffset,
maxXOffset,
minYOffset,
maxYOffset,
// Hash function
hash = sha1,
// Domain hash value
domainHash,
// Domain unique user ID
domainUserId,
// ID for the current session
memorizedSessionId,
// Index for the current session - kept in memory in case cookies are disabled
memorizedVisitCount = 1,
// Business-defined unique user ID
businessUserId,
// Ecommerce transaction data
// Will be committed, sent and emptied by a call to trackTrans.
ecommerceTransaction = ecommerceTransactionTemplate(),
// Manager for automatic link click tracking
linkTrackingManager = links.getLinkTrackingManager(core, trackerId, addCommonContexts),
// Manager for automatic form tracking
formTrackingManager = forms.getFormTrackingManager(core, trackerId, addCommonContexts),
// Manager for tracking unhandled exceptions
errorManager = errors.errorManager(core),
// Manager for local storage queue
outQueueManager = new requestQueue.OutQueueManager(
functionName,
namespace,
mutSnowplowState,
configStateStorageStrategy == 'localStorage' ||
configStateStorageStrategy == 'cookieAndLocalStorage',
argmap.post,
argmap.bufferSize,
argmap.maxPostBytes || 40000),
// Flag to prevent the geolocation context being added multiple times
geolocationContextAdded = false,
// Set of contexts to be added to every event
autoContexts = argmap.contexts || {},
// Context to be added to every event
commonContexts = [],
// Enhanced Ecommerce Contexts to be added on every `trackEnhancedEcommerceAction` call
enhancedEcommerceContexts = [],
// Whether pageViewId should be regenerated after each trackPageView. Affect web_page context
preservePageViewId = false;
if (argmap.hasOwnProperty('discoverRootDomain') && argmap.discoverRootDomain) {
configCookieDomain = helpers.findRootDomain();
}
if (autoContexts.gaCookies) {
commonContexts.push(getGaCookiesContext());
}
if (autoContexts.geolocation) {
enableGeolocationContext();
}
// Enable base 64 encoding for self-describing events and custom contexts
core.setBase64Encoding(argmap.hasOwnProperty('encodeBase64') ? argmap.encodeBase64 : true);
// Set up unchanging name-value pairs
core.setTrackerVersion(version);
core.setTrackerNamespace(namespace);
core.setAppId(configTrackerSiteId);
core.setPlatform(configPlatform);
core.setTimezone(detectors.detectTimezone());
core.addPayloadPair('lang', browserLanguage);
core.addPayloadPair('cs', documentCharset);
// Browser features. Cookies, color depth and resolution don't get prepended with f_ (because they're not optional features)
for (var i in browserFeatures) {
if (Object.prototype.hasOwnProperty.call(browserFeatures, i)) {
if (i === 'res' || i === 'cd' || i === 'cookie') {
core.addPayloadPair(i, browserFeatures[i]);
} else {
core.addPayloadPair('f_' + i, browserFeatures[i]);
}
}
}
/**
* Recalculate the domain, URL, and referrer
*/
function refreshUrl() {
locationArray = proxies.fixupUrl(documentAlias.domain, windowAlias.location.href, helpers.getReferrer());
// If this is a single-page app and the page URL has changed, then:
// - if the new URL's querystring contains a "refer(r)er" parameter, use it as the referrer
// - otherwise use the old URL as the referer
if (locationArray[1] !== locationHrefAlias) {
configReferrerUrl = helpers.getReferrer(locationHrefAlias);
}
domainAlias = helpers.fixupDomain(locationArray[0]);
locationHrefAlias = locationArray[1];
}
/**
* Decorate the querystring of a single link
*
* @param event e The event targeting the link
*/
function linkDecorationHandler() {
var tstamp = new Date().getTime();
if (this.href) {
this.href = helpers.decorateQuerystring(this.href, '_sp', domainUserId + '.' + tstamp);
}
}
/**
* Enable querystring decoration for links pasing a filter
* Whenever such a link is clicked on or navigated to via the keyboard,
* add "_sp={{duid}}.{{timestamp}}" to its querystring
*
* @param crossDomainLinker Function used to determine which links to decorate
*/
function decorateLinks(crossDomainLinker) {
for (var i=0; i<documentAlias.links.length; i++) {
var elt = documentAlias.links[i];
if (!elt.spDecorationEnabled && crossDomainLinker(elt)) {
helpers.addEventListener(elt, 'click', linkDecorationHandler, true);
helpers.addEventListener(elt, 'mousedown', linkDecorationHandler, true);
// Don't add event listeners more than once
elt.spDecorationEnabled = true;
}
}
}
/*
* Initializes an empty ecommerce
* transaction and line items
*/
function ecommerceTransactionTemplate() {
return {
transaction: {},
items: []
};
}
/*
* Removes hash tag from the URL
*
* URLs are purified before being recorded in the cookie,
* or before being sent as GET parameters
*/
function purify(url) {
var targetPattern;
if (configDiscardHashTag) {
targetPattern = new RegExp('#.*');
return url.replace(targetPattern, '');
}
return url;
}
/*
* Extract scheme/protocol from URL
*/
function getProtocolScheme(url) {
var e = new RegExp('^([a-z]+):'),
matches = e.exec(url);
return matches ? matches[1] : null;
}
/*
* Resolve relative reference
*
* Note: not as described in rfc3986 section 5.2
*/
function resolveRelativeReference(baseUrl, url) {
var protocol = getProtocolScheme(url),
i;
if (protocol) {
return url;
}
if (url.slice(0, 1) === '/') {
return getProtocolScheme(baseUrl) + '://' + helpers.getHostName(baseUrl) + url;
}
baseUrl = purify(baseUrl);
if ((i = baseUrl.indexOf('?')) >= 0) {
baseUrl = baseUrl.slice(0, i);
}
if ((i = baseUrl.lastIndexOf('/')) !== baseUrl.length - 1) {
baseUrl = baseUrl.slice(0, i + 1);
}
return baseUrl + url;
}
/*
* Send request
*/
function sendRequest(request, delay) {
var now = new Date();
if (!(configDoNotTrack || !!getSnowplowCookieValue(configOptOutCookie))) {
outQueueManager.enqueueRequest(request.build(), configCollectorUrl);
mutSnowplowState.expireDateTime = now.getTime() + delay;
}
}
/*
* Get cookie name with prefix and domain hash
*/
function getSnowplowCookieName(baseName) {
return configCookieNamePrefix + baseName + '.' + domainHash;
}
/*
* Cookie getter.
*/
function getSnowplowCookieValue(cookieName) {
if (configStateStorageStrategy == 'localStorage') {
return helpers.attemptGetLocalStorage(cookieName);
} else if (configStateStorageStrategy == 'cookie' ||
configStateStorageStrategy == 'cookieAndLocalStorage') {
return cookie.cookie(getSnowplowCookieName(cookieName));
}
}
/*
* Update domain hash
*/
function updateDomainHash() {
refreshUrl();
domainHash = hash((configCookieDomain || domainAlias) + (configCookiePath || '/')).slice(0, 4); // 4 hexits = 16 bits
}
/*
* Process all "activity" events.
* For performance, this function must have low overhead.
*/
function activityHandler() {
var now = new Date();
lastActivityTime = now.getTime();
}
/*
* Process all "scroll" events.
*/
function scrollHandler() {
updateMaxScrolls();
activityHandler();
}
/*
* Returns [pageXOffset, pageYOffset].
* Adapts code taken from: http://www.javascriptkit.com/javatutors/static2.shtml
*/
function getPageOffsets() {
var iebody = (documentAlias.compatMode && documentAlias.compatMode !== "BackCompat") ?
documentAlias.documentElement :
documentAlias.body;
return [iebody.scrollLeft || windowAlias.pageXOffset, iebody.scrollTop || windowAlias.pageYOffset];
}
/*
* Quick initialization/reset of max scroll levels
*/
function resetMaxScrolls() {
var offsets = getPageOffsets();
var x = offsets[0];
minXOffset = x;
maxXOffset = x;
var y = offsets[1];
minYOffset = y;
maxYOffset = y;
}
/*
* Check the max scroll levels, updating as necessary
*/
function updateMaxScrolls() {
var offsets = getPageOffsets();
var x = offsets[0];
if (x < minXOffset) {
minXOffset = x;
} else if (x > maxXOffset) {
maxXOffset = x;
}
var y = offsets[1];
if (y < minYOffset) {
minYOffset = y;
} else if (y > maxYOffset) {
maxYOffset = y;
}
}
/*
* Prevents offsets from being decimal or NaN
* See https://github.com/snowplow/snowplow-javascript-tracker/issues/324
* TODO: the NaN check should be moved into the core
*/
function cleanOffset(offset) {
var rounded = Math.round(offset);
if (!isNaN(rounded)) {
return rounded;
}
}
/*
* Sets or renews the session cookie
*/
function setSessionCookie() {
var cookieName = getSnowplowCookieName('ses');
var cookieValue = '*';
setCookie(cookieName, cookieValue, configSessionCookieTimeout);
}
/*
* Sets the Visitor ID cookie: either the first time loadDomainUserIdCookie is called
* or when there is a new visit or a new page view
*/
function setDomainUserIdCookie(_domainUserId, createTs, visitCount, nowTs, lastVisitTs, sessionId) {
var cookieName = getSnowplowCookieName('id');
var cookieValue = _domainUserId + '.' + createTs + '.' + visitCount + '.' + nowTs +
'.' + lastVisitTs + '.' + sessionId;
setCookie(cookieName, cookieValue, configVisitorCookieTimeout);
}
/*
* Sets a cookie based on the storage strategy:
* - if 'localStorage': attemps to write to local storage
* - if 'cookie': writes to cookies
* - otherwise: no-op
*/
function setCookie(name, value, timeout) {
if (configStateStorageStrategy == 'localStorage') {
helpers.attemptWriteLocalStorage(name, value);
} else if (configStateStorageStrategy == 'cookie' ||
configStateStorageStrategy == 'cookieAndLocalStorage') {
cookie.cookie(name, value, timeout, configCookiePath, configCookieDomain);
}
}
/**
* Generate a pseudo-unique ID to fingerprint this user
*/
function createNewDomainUserId() {
return uuid.v4();
}
/*
* Load the domain user ID and the session ID
* Set the cookies (if cookies are enabled)
*/
function initializeIdsAndCookies() {
var sesCookieSet =
configStateStorageStrategy != 'none' && !!getSnowplowCookieValue('ses');
var idCookieComponents = loadDomainUserIdCookie();
if (idCookieComponents[1]) {
domainUserId = idCookieComponents[1];
} else {
domainUserId = createNewDomainUserId();
idCookieComponents[1] = domainUserId;
}
memorizedSessionId = idCookieComponents[6];
if (!sesCookieSet) {
// Increment the session ID
idCookieComponents[3] ++;
// Create a new sessionId
memorizedSessionId = uuid.v4();
idCookieComponents[6] = memorizedSessionId;
// Set lastVisitTs to currentVisitTs
idCookieComponents[5] = idCookieComponents[4];
}
if (configStateStorageStrategy != 'none') {
setSessionCookie();
// Update currentVisitTs
idCookieComponents[4] = Math.round(new Date().getTime() / 1000);
idCookieComponents.shift();
setDomainUserIdCookie.apply(null, idCookieComponents);
}
}
/*
* Load visitor ID cookie
*/
function loadDomainUserIdCookie() {
if (configStateStorageStrategy == 'none') {
return [];
}
var now = new Date(),
nowTs = Math.round(now.getTime() / 1000),
id = getSnowplowCookieValue('id'),
tmpContainer;
if (id) {
tmpContainer = id.split('.');
// cookies enabled
tmpContainer.unshift('0');
} else {
tmpContainer = [
// cookies disabled
'1',
// Domain user ID
domainUserId,
// Creation timestamp - seconds since Unix epoch
nowTs,
// visitCount - 0 = no previous visit
0,
// Current visit timestamp
nowTs,
// Last visit timestamp - blank meaning no previous visit
''
];
}
if (!tmpContainer[6]) {
// session id
tmpContainer[6] = uuid.v4();
}
return tmpContainer;
}
/*
* Attaches common web fields to every request
* (resolution, url, referrer, etc.)
* Also sets the required cookies.
*/
function addBrowserData(sb) {
var nowTs = Math.round(new Date().getTime() / 1000),
idname = getSnowplowCookieName('id'),
sesname = getSnowplowCookieName('ses'),
ses = getSnowplowCookieValue('ses'),
id = loadDomainUserIdCookie(),
cookiesDisabled = id[0],
_domainUserId = id[1], // We could use the global (domainUserId) but this is better etiquette
createTs = id[2],
visitCount = id[3],
currentVisitTs = id[4],
lastVisitTs = id[5],
sessionIdFromCookie = id[6];
if ((configDoNotTrack || !!getSnowplowCookieValue(configOptOutCookie)) &&
configStateStorageStrategy != 'none') {
if (configStateStorageStrategy == 'localStorage') {
helpers.attemptWriteLocalStorage(idname, '');
helpers.attemptWriteLocalStorage(sesName, '');
} else if (configStateStorageStrategy == 'cookie' ||
configStateStorageStrategy == 'cookieAndLocalStorage') {
cookie.cookie(idname, '', -1, configCookiePath, configCookieDomain);
cookie.cookie(sesname, '', -1, configCookiePath, configCookieDomain);
}
return;
}
// If cookies are enabled, base visit count and session ID on the cookies
if (cookiesDisabled === '0') {
memorizedSessionId = sessionIdFromCookie;
// New session?
if (!ses && configStateStorageStrategy != 'none') {
// New session (aka new visit)
visitCount++;
// Update the last visit timestamp
lastVisitTs = currentVisitTs;
// Regenerate the session ID
memorizedSessionId = uuid.v4();
}
memorizedVisitCount = visitCount;
// Otherwise, a new session starts if configSessionCookieTimeout seconds have passed since the last event
} else {
if ((new Date().getTime() - lastEventTime) > configSessionCookieTimeout * 1000) {
memorizedSessionId = uuid.v4();
memorizedVisitCount++;
}
}
// Build out the rest of the request
sb.add('vp', detectors.detectViewport());
sb.add('ds', detectors.detectDocumentSize());
sb.add('vid', memorizedVisitCount);
sb.add('sid', memorizedSessionId);
sb.add('duid', _domainUserId); // Set to our local variable
sb.add('fp', userFingerprint);
sb.add('uid', businessUserId);
refreshUrl();
sb.add('refr', purify(customReferrer || configReferrerUrl));
// Add the page URL last as it may take us over the IE limit (and we don't always need it)
sb.add('url', purify(configCustomUrl || locationHrefAlias));
// Update cookies
if (configStateStorageStrategy != 'none') {
setDomainUserIdCookie(_domainUserId, createTs, memorizedVisitCount, nowTs,
lastVisitTs, memorizedSessionId);
setSessionCookie();
}
lastEventTime = new Date().getTime();
}
/**
* Builds a collector URL from a CloudFront distribution.
* We don't bother to support custom CNAMEs because Amazon CloudFront doesn't support that for SSL.
*
* @param string account The account ID to build the tracker URL from
*
* @return string The URL on which the collector is hosted
*/
function collectorUrlFromCfDist(distSubdomain) {
return asCollectorUrl(distSubdomain + '.cloudfront.net');
}
/**
* Adds the protocol in front of our collector URL, and i to the end
*
* @param string rawUrl The collector URL without protocol
*
* @return string collectorUrl The tracker URL with protocol
*/
function asCollectorUrl(rawUrl) {
if (forceSecureTracker) {
return ('https' + '://' + rawUrl);
}
if (forceUnsecureTracker) {
return ('http' + '://' + rawUrl);
}
return ('https:' === documentAlias.location.protocol ? 'https' : 'http') + '://' + rawUrl;
}
/**
* Add common contexts to every event
* TODO: move this functionality into the core
*
* @param array userContexts List of user-defined contexts
* @return userContexts combined with commonContexts
*/
function addCommonContexts(userContexts) {
var combinedContexts = commonContexts.concat(userContexts || []);
if (autoContexts.webPage) {
combinedContexts.push(getWebPageContext());
}
// Add PerformanceTiming Context
if (autoContexts.performanceTiming) {
var performanceTimingContext = getPerformanceTimingContext();
if (performanceTimingContext) {
combinedContexts.push(performanceTimingContext);
}
}
// Add Optimizely Contexts
if (windowAlias.optimizely) {
if (autoContexts.optimizelySummary) {
var activeExperiments = getOptimizelySummaryContexts();
lodash.each(activeExperiments, function (e) {
combinedContexts.push(e)
})
}
if (autoContexts.optimizelyXSummary) {
var activeExperiments = getOptimizelyXSummaryContexts();
lodash.each(activeExperiments, function (e) {
combinedContexts.push(e);
})
}
if (autoContexts.optimizelyExperiments) {
var experimentContexts = getOptimizelyExperimentContexts();
for (var i = 0; i < experimentContexts.length; i++) {
combinedContexts.push(experimentContexts[i]);
}
}
if (autoContexts.optimizelyStates) {
var stateContexts = getOptimizelyStateContexts();
for (var i = 0; i < stateContexts.length; i++) {
combinedContexts.push(stateContexts[i]);
}
}
if (autoContexts.optimizelyVariations) {
var variationContexts = getOptimizelyVariationContexts();
for (var i = 0; i < variationContexts.length; i++) {
combinedContexts.push(variationContexts[i]);
}
}
if (autoContexts.optimizelyVisitor) {
var optimizelyVisitorContext = getOptimizelyVisitorContext();
if (optimizelyVisitorContext) {
combinedContexts.push(optimizelyVisitorContext);
}
}
if (autoContexts.optimizelyAudiences) {
var audienceContexts = getOptimizelyAudienceContexts();
for (var i = 0; i < audienceContexts.length; i++) {
combinedContexts.push(audienceContexts[i]);
}
}
if (autoContexts.optimizelyDimensions) {
var dimensionContexts = getOptimizelyDimensionContexts();
for (var i = 0; i < dimensionContexts.length; i++) {
combinedContexts.push(dimensionContexts[i]);
}
}
}
// Add Augur Context
if (autoContexts.augurIdentityLite) {
var augurIdentityLiteContext = getAugurIdentityLiteContext();
if (augurIdentityLiteContext) {
combinedContexts.push(augurIdentityLiteContext);
}
}
//Add Parrable Context
if (autoContexts.parrable) {
var parrableContext = getParrableContext();
if (parrableContext) {
combinedContexts.push(parrableContext);
}
}
return combinedContexts;
}
/**
* Initialize new `pageViewId` if it shouldn't be preserved.
* Should be called when `trackPageView` is invoked
*/
function resetPageView() {
if (!preservePageViewId || mutSnowplowState.pageViewId == null) {
mutSnowplowState.pageViewId = uuid.v4();
}
}
/**
* Safe function to get `pageViewId`.
* Generates it if it wasn't initialized by other tracker
*/
function getPageViewId() {
if (mutSnowplowState.pageViewId == null) {
mutSnowplowState.pageViewId = uuid.v4();
}
return mutSnowplowState.pageViewId
}
/**
* Put together a web page context with a unique UUID for the page view
*
* @return object web_page context
*/
function getWebPageContext() {
return {
schema: 'iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0',
data: {
id: getPageViewId()
}
};
}
/**
* Creates a context from the window.performance.timing object
*
* @return object PerformanceTiming context
*/
function getPerformanceTimingContext() {
var allowedKeys = [
'navigationStart', 'redirectStart', 'redirectEnd', 'fetchStart', 'domainLookupStart', 'domainLookupEnd', 'connectStart',
'secureConnectionStart', 'connectEnd', 'requestStart', 'responseStart', 'responseEnd', 'unloadEventStart', 'unloadEventEnd',
'domLoading', 'domInteractive', 'domContentLoadedEventStart', 'domContentLoadedEventEnd', 'domComplete', 'loadEventStart',
'loadEventEnd', 'msFirstPaint', 'chromeFirstPaint', 'requestEnd', 'proxyStart', 'proxyEnd'
];
var performance = windowAlias.performance || windowAlias.mozPerformance || windowAlias.msPerformance || windowAlias.webkitPerformance;
if (performance) {
// On Safari, the fields we are interested in are on the prototype chain of
// performance.timing so we cannot copy them using lodash.clone
var performanceTiming = {};
for (var field in performance.timing) {
if (helpers.isValueInArray(field, allowedKeys)) {
performanceTiming[field] = performance.timing[field];
}
}
// Old Chrome versions add an unwanted requestEnd field
delete performanceTiming.requestEnd;
// Add the Chrome firstPaintTime to the performance if it exists
if (windowAlias.chrome && windowAlias.chrome.loadTimes && typeof windowAlias.chrome.loadTimes().firstPaintTime === 'number') {
performanceTiming.chromeFirstPaint = Math.round(windowAlias.chrome.loadTimes().firstPaintTime * 1000);
}
return {
schema: 'iglu:org.w3/PerformanceTiming/jsonschema/1-0-0',
data: performanceTiming
};
}
}
/**
* Check that *both* optimizely and optimizely.data exist and return
* optimizely.data.property
*
* @param property optimizely data property
* @param snd optional nested property
*/
function getOptimizelyData(property, snd) {
var data;
if (windowAlias.optimizely && windowAlias.optimizely.data) {
data = windowAlias.optimizely.data[property];
if (typeof snd !== 'undefined' && data !== undefined) {
data = data[snd]
}
}
return data
}
/**
* Check that *both* optimizely and optimizely.data exist
*
* @param property optimizely data property
* @param snd optional nested property
*/
function getOptimizelyXData(property, snd) {
var data;
if (windowAlias.optimizely) {
data = windowAlias.optimizely.get(property);
if (typeof snd !== 'undefined' && data !== undefined) {
data = data[snd]