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
1824 lines (1598 loc) · 52.3 KB
/
Copy pathtracker.js
File metadata and controls
1824 lines (1598 loc) · 52.3 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-2013 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.
*/
/*
* SnowPlow Tracker class
*
* Takes an argmap as its sole parameter. Argmap supports:
*
* 1. Empty - to initialize an Async Tracker
* 2. {cf: 'subdomain'} - to initialize a Sync Tracker with
* a CloudFront-based collector
* 3. {url: 'rawurl'} - to initialize a Sync Tracker with a
* URL-based collector
*
* See also: Tracker.setCollectorUrl() and Tracker.setCollectorCf()
*/
SnowPlow.Tracker = function Tracker(argmap) {
/************************************************************
* Private members
************************************************************/
var
/*<DEBUG>*/
/*
* registered test hooks
*/
registeredHooks = {},
/*</DEBUG>*/
// Current URL and Referrer URL
locationArray = SnowPlow.fixupUrl(SnowPlow.documentAlias.domain, SnowPlow.windowAlias.location.href, SnowPlow.getReferrer()),
domainAlias = SnowPlow.fixupDomain(locationArray[0]),
locationHrefAlias = locationArray[1],
configReferrerUrl = locationArray[2],
// Request method is always GET for SnowPlow
configRequestMethod = 'GET',
// Platform is always web for this tracker
configPlatform = 'web',
// SnowPlow collector URL
configCollectorUrl = constructCollectorUrl(argmap),
// Site ID
configTrackerSiteId = '', // Updated for SnowPlow
// Document URL
configCustomUrl,
// Document title
configTitle = SnowPlow.documentAlias.title,
// Extensions to be treated as download links
configDownloadExtensions = '7z|aac|ar[cj]|as[fx]|avi|bin|csv|deb|dmg|doc|exe|flv|gif|gz|gzip|hqx|jar|jpe?g|js|mp(2|3|4|e?g)|mov(ie)?|ms[ip]|od[bfgpst]|og[gv]|pdf|phps|png|ppt|qtm?|ra[mr]?|rpm|sea|sit|tar|t?bz2?|tgz|torrent|txt|wav|wm[av]|wpd||xls|xml|z|zip',
// Hosts or alias(es) to not treat as outlinks
configHostsAlias = [domainAlias],
// HTML anchor element classes to not track
configIgnoreClasses = [],
// HTML anchor element classes to treat as downloads
configDownloadClasses = [],
// HTML anchor element classes to treat at outlinks
configLinkClasses = [],
// Maximum delay to wait for web bug image to be fetched (in milliseconds)
configTrackerPause = 500,
// Minimum visit time after initial page view (in milliseconds)
configMinimumVisitTime,
// Recurring heart beat after initial ping (in milliseconds)
configHeartBeatTimer,
// Disallow hash tags in URL
configDiscardHashTag,
// First-party cookie name prefix
configCookieNamePrefix = '_sp_',
// First-party cookie domain
// User agent defaults to origin hostname
configCookieDomain,
// First-party cookie path
// Default is user agent defined.
configCookiePath,
// Do Not Track
configDoNotTrack,
// Count sites which are pre-rendered
configCountPreRendered,
// Life of the visitor cookie (in milliseconds)
configVisitorCookieTimeout = 63072000000, // 2 years
// Life of the session cookie (in milliseconds)
configSessionCookieTimeout = 1800000, // 30 minutes
// Life of the referral cookie (in milliseconds)
configReferralCookieTimeout = 15768000000, // 6 months
// Enable Base64 encoding for unstructured events
configEncodeBase64 = true,
// Document character set
documentCharset = SnowPlow.documentAlias.characterSet || SnowPlow.documentAlias.charset,
// Browser language (or Windows language for IE). Imperfect but CloudFront doesn't log the Accept-Language header
browserLanguage = SnowPlow.navigatorAlias.userLanguage || SnowPlow.navigatorAlias.language,
// Browser features via client-side data collection
browserFeatures = detectBrowserFeatures(),
// Visitor timezone
timezone = detectTimezone(),
// Visitor fingerprint
fingerprint = generateFingerprint(),
// Guard against installing the link tracker more than once per Tracker instance
linkTrackingInstalled = false,
// Guard against installing the activity tracker more than once per Tracker instance
activityTrackingInstalled = false,
// Last activity timestamp
lastActivityTime,
// How are we scrolling?
minXOffset,
maxXOffset,
minYOffset,
maxYOffset,
// Internal state of the pseudo click handler
lastButton,
lastTarget,
// Hash function
hash = SnowPlow.sha1,
// Domain hash value
domainHash,
// Domain unique user ID
domainUserId,
// Business-defined unique user ID
businessUserId,
// Ecommerce transaction data
// Will be committed, sent and emptied by a call to trackTrans.
ecommerceTransaction = ecommerceTransactionTemplate();
/**
* Determines how to build our collector URL,
* based on the argmap passed into the
* Tracker's constructor.
*/
function constructCollectorUrl(argmap) {
if (typeof argmap === "undefined") {
return null; // JavaScript joys, changing an undefined into a null
} else if ('cf' in argmap) {
return collectorUrlFromCfDist(argmap.cf);
} else if ('url' in argmap) {
return asCollectorUrl(argmap.url);
}
}
/*
* 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) + '://' + SnowPlow.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;
}
/*
* Is the host local? (i.e., not an outlink)
*
* This is a pretty flawed approach - assumes
* a website only has one domain.
*
* TODO: I think we can blow this away for
* SnowPlow and handle the equivalent with a
* whitelist of the site's domains.
*
*/
function isSiteHostName(hostName) {
var i,
alias,
offset;
for (i = 0; i < configHostsAlias.length; i++) {
alias = SnowPlow.fixupDomain(configHostsAlias[i].toLowerCase());
if (hostName === alias) {
return true;
}
if (alias.slice(0, 1) === '.') {
if (hostName === alias.slice(1)) {
return true;
}
offset = hostName.length - alias.length;
if ((offset > 0) && (hostName.slice(offset) === alias)) {
return true;
}
}
}
return false;
}
/*
* Send image request to the SnowPlow Collector using GET.
* The Collector serves a transparent, single pixel (1x1) GIF
*/
function getImage(request) {
var image = new Image(1, 1);
// Let's chec that we have a Url to ping
if (configCollectorUrl === null) {
throw "No SnowPlow collector configured, cannot track";
}
// Okay? Let's proceed.
image.onload = function () { };
image.src = configCollectorUrl + request;
}
/*
* Send request
*/
function sendRequest(request, delay) {
var now = new Date();
if (!configDoNotTrack) {
getImage(request);
SnowPlow.expireDateTime = now.getTime() + delay;
}
}
/*
* Get cookie name with prefix and domain hash
*/
function getCookieName(baseName) {
return configCookieNamePrefix + baseName + '.' + domainHash;
}
/*
* Legacy getCookieName. This is the old version inherited from
* Piwik which includes the site ID. Including the site ID in
* the user cookie doesn't make sense, so we have removed it.
* But, to avoid breaking sites with existing cookies, we leave
* this function in as a legacy, and use it to check for a
* 'legacy' cookie.
*
* TODO: delete in February 2013 or so!
*/
function getLegacyCookieName(baseName) {
return configCookieNamePrefix + baseName + '.' + configTrackerSiteId + '.' + domainHash;
}
/*
* Cookie getter.
*
* This exists because we cannot guarantee whether a cookie will
* be available using getCookieName or getLegacyCookieName (i.e.
* whether the cookie includes the legacy site ID in its name).
*
* This wrapper supports both.
*
* TODO: simplify in February 2013 back to:
* return SnowPlow.getCookie(getCookieName(cookieName));
*/
function getCookieValue(cookieName) {
// First we try the new cookie
var cookieValue = SnowPlow.getCookie(getCookieName(cookieName));
if (cookieValue) {
return cookieValue;
}
// Last we try the legacy cookie. May still return failure.
return SnowPlow.getCookie(getLegacyCookieName(cookieName));
}
/*
* Does browser have cookies enabled (for this site)?
*/
function hasCookies() {
var testCookieName = getCookieName('testcookie');
if (!SnowPlow.isDefined(SnowPlow.navigatorAlias.cookieEnabled)) {
SnowPlow.setCookie(testCookieName, '1');
return SnowPlow.getCookie(testCookieName) === '1' ? '1' : '0';
}
return SnowPlow.navigatorAlias.cookieEnabled ? '1' : '0';
}
/*
* Update domain hash
*/
function updateDomainHash() {
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 = (SnowPlow.documentAlias.compatMode && SnowPlow.documentAlias.compatMode != "BackCompat") ?
SnowPlow.documentAlias.documentElement :
SnowPlow.documentAlias.body;
return [iebody.scrollLeft || SnowPlow.windowAlias.pageXOffset,
iebody.scrollTop || SnowPlow.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;
}
}
/*
* 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) {
SnowPlow.setCookie(getCookieName('id'), _domainUserId + '.' + createTs + '.' + visitCount + '.' + nowTs + '.' + lastVisitTs, configVisitorCookieTimeout, configCookiePath, configCookieDomain);
}
/*
* Load visitor ID cookie
*/
function loadDomainUserIdCookie() {
var now = new Date(),
nowTs = Math.round(now.getTime() / 1000),
id = getCookieValue('id'),
tmpContainer;
if (id) {
tmpContainer = id.split('.');
// New visitor set to 0 now
tmpContainer.unshift('0');
} else {
// Domain - generate a pseudo-unique ID to fingerprint this user;
// Note: this isn't a RFC4122-compliant UUID
if (!domainUserId) {
domainUserId = hash(
(SnowPlow.navigatorAlias.userAgent || '') +
(SnowPlow.navigatorAlias.platform || '') +
JSON2.stringify(browserFeatures) + nowTs
).slice(0, 16); // 16 hexits = 64 bits
}
tmpContainer = [
// New visitor
'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
''
];
}
return tmpContainer;
}
/*
* Get the current timestamp:
* milliseconds since epoch.
*/
function getTimestamp() {
var now = new Date(),
nowTs = now.getTime();
return nowTs;
}
/*
* Attaches all the common web fields to the request
* (resolution, url, referrer, etc.)
* Also sets the required cookies.
*
* Takes in a string builder, adds in parameters to it
* and then generates the request.
*/
function getRequest(sb, pluginMethod) {
var i,
now = new Date(),
nowTs = Math.round(now.getTime() / 1000),
newVisitor,
_domainUserId, // Don't shadow the global
visitCount,
createTs,
currentVisitTs,
lastVisitTs,
referralTs,
referralUrl,
referralUrlMaxLength = 1024,
currentReferrerHostName,
originalReferrerHostName,
idname = getCookieName('id'),
sesname = getCookieName('ses'), // NOT sesname
id = loadDomainUserIdCookie(),
ses = getCookieValue('ses'),
currentUrl = configCustomUrl || locationHrefAlias,
featurePrefix;
if (configDoNotTrack) {
SnowPlow.setCookie(idname, '', -1, configCookiePath, configCookieDomain);
SnowPlow.setCookie(sesname, '', -1, configCookiePath, configCookieDomain);
return '';
}
newVisitor = 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];
// New session
if (!ses) {
// New session (aka new visit)
visitCount++;
// Update the last visit timestamp
lastVisitTs = currentVisitTs;
}
// Build out the rest of the request - first add fields we can safely skip encoding
sb.addRaw('dtm', getTimestamp());
sb.addRaw('tid', String(Math.random()).slice(2, 8));
sb.addRaw('vp', detectViewport());
sb.addRaw('ds', detectDocumentSize());
sb.addRaw('vid', visitCount);
sb.addRaw('duid', _domainUserId); // Set to our local variable
// Encode all these
sb.add('p', configPlatform);
sb.add('tv', SnowPlow.version);
sb.add('fp', fingerprint);
sb.add('aid', configTrackerSiteId);
sb.add('lang', browserLanguage);
sb.add('cs', documentCharset);
sb.add('tz', timezone);
sb.add('uid', businessUserId); // Business-defined user ID
// Adds with custom conditions
if (configReferrerUrl.length) sb.add('refr', purify(configReferrerUrl));
// Browser features. Cookies, color depth and resolution don't get prepended with f_ (because they're not optional features)
for (i in browserFeatures) {
if (Object.prototype.hasOwnProperty.call(browserFeatures, i)) {
featurePrefix = (i === 'res' || i === 'cd' || i === 'cookie') ? '' : 'f_';
sb.addRaw(featurePrefix + i, browserFeatures[i]);
}
}
// 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(currentUrl));
var request = sb.build();
// Update cookies
setDomainUserIdCookie(_domainUserId, createTs, visitCount, nowTs, lastVisitTs);
SnowPlow.setCookie(sesname, '*', configSessionCookieTimeout, configCookiePath, configCookieDomain);
// Tracker plugin hook
// TODO: we can blow this away for SnowPlow
request += SnowPlow.executePluginMethod(pluginMethod);
return request;
}
/**
* 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) {
return ('https:' == SnowPlow.documentAlias.location.protocol ? 'https' : 'http') + '://' + rawUrl + '/i';
}
/**
* A helper to build a SnowPlow request string from an
* an optional initial value plus a set of individual
* name-value pairs, provided using the add method.
*
* @param string initialValue The initial querystring, ready to have additional key-value pairs added
*
* @return object The request string builder, with add, addRaw and build methods
*/
function requestStringBuilder(initialValue) {
var str = initialValue || '';
var addNvPair = function(key, value, encode) {
if (value !== undefined && value !== '') {
var sep = (str.length > 0) ? "&" : "?";
str += sep + key + '=' + (encode ? SnowPlow.encodeWrapper(value) : value);
}
};
return {
add: function(key, value) {
addNvPair(key, value, true);
},
addRaw: function(key, value) {
addNvPair(key, value, false);
},
build: function() {
return str;
}
}
}
/**
* Log a structured event happening on this page
*
* @param string category The name you supply for the group of objects you want to track
* @param string action A string that is uniquely paired with each category, and commonly used to define the type of user interaction for the web object
* @param string label (optional) An optional string to provide additional dimensions to the event data
* @param string property (optional) Describes the object or the action performed on it, e.g. quantity of item added to basket
* @param numeric value (optional) An integer or floating point number to provide numerical data about the user event
*/
function logStructEvent(category, action, label, property, value) {
var sb = requestStringBuilder();
sb.add('e', 'se'); // 'se' for Structured Event
sb.add('se_ca', category);
sb.add('se_ac', action)
sb.add('se_la', label);
sb.add('se_pr', property);
sb.add('se_va', value);
request = getRequest(sb, 'structEvent');
sendRequest(request, configTrackerPause);
}
/**
* Log an unstructured event happening on this page
*
* @param string name The name of the event
* @param object properties The properties of the event
*/
function logUnstructEvent(name, properties) {
var sb = requestStringBuilder();
sb.add('e', 'ue'); // 'ue' for Unstructured Event
sb.add('ue_na', name);
var translated = {}
for(var p in properties) {
var key = p, value = properties[p];
if (properties.hasOwnProperty(p) && SnowPlow.isDate(properties[p])) {
type = SnowPlow.getPropertySuffix(p);
if(!type) {
type = 'tms'
key += '$' + type
}
value = SnowPlow.translateDateValue(value, type);
};
translated[key] = value;
}
pr_string = JSON2.stringify(translated);
if(configEncodeBase64) {
sb.addRaw('ue_px', SnowPlow.base64urlencode(pr_string));
} else {
sb.add('ue_pr', pr_string);
};
request = getRequest(sb, 'unstructEvent');
sendRequest(request, configTrackerPause);
}
/**
* Log an ad impression
*
* @param string bannerId Identifier for the ad banner displayed
* @param string campaignId (optional) Identifier for the campaign which the banner belongs to
* @param string advertiserId (optional) Identifier for the advertiser which the campaign belongs to
* @param string userId (optional) Ad server identifier for the viewer of the banner
*/
// TODO: rename to logAdImpression and deprecate logImpression
// TODO: should add impressionId as well.
// TODO: should add in zoneId (aka placementId, slotId?) as well
// TODO: change ad_ to ai_?
function logImpression(bannerId, campaignId, advertiserId, userId) {
var sb = requestStringBuilder();
sb.add('e', 'ad'); // 'ad' for AD impression
sb.add('ad_ba', bannerId);
sb.add('ad_ca', campaignId)
sb.add('ad_ad', advertiserId);
sb.add('ad_uid', userId);
request = getRequest(sb, 'impression');
sendRequest(request, configTrackerPause);
}
// TODO: add in ad clicks
/**
* Log ecommerce transaction metadata
*
* @param string orderId
* @param string affiliation
* @param string total
* @param string tax
* @param string shipping
* @param string city
* @param string state
* @param string country
*/
// TODO: add params to comment
function logTransaction(orderId, affiliation, total, tax, shipping, city, state, country) {
var sb = requestStringBuilder();
sb.add('e', 'tr'); // 'tr' for TRansaction
sb.add('tr_id', orderId);
sb.add('tr_af', affiliation);
sb.add('tr_tt', total);
sb.add('tr_tx', tax);
sb.add('tr_sh', shipping);
sb.add('tr_ci', city);
sb.add('tr_st', state);
sb.add('tr_co', country);
var request = getRequest(sb, 'transaction');
sendRequest(request, configTrackerPause);
}
/**
* Log ecommerce transaction item
*
* @param string orderId
* @param string sku
* @param string name
* @param string category
* @param string price
* @param string quantity
*/
// TODO: add params to comment
function logTransactionItem(orderId, sku, name, category, price, quantity) {
var sb = requestStringBuilder();
sb.add('e', 'ti'); // 'ti' for Transaction Item
sb.add('ti_id', orderId);
sb.add('ti_sk', sku);
sb.add('ti_na', name);
sb.add('ti_ca', category);
sb.add('ti_pr', price);
sb.add('ti_qu', quantity);
var request = getRequest(sb, 'transactionItem');
sendRequest(request, configTrackerPause);
}
/*
* Log the page view / visit
*
* @param string customTitle The user-defined page title to attach to this page view
*/
function logPageView(customTitle) {
// Fixup page title. We'll pass this to logPagePing too.
var pageTitle = SnowPlow.fixupTitle(customTitle || configTitle);
// Log page view
var sb = requestStringBuilder();
sb.add('e', 'pv'); // 'pv' for Page View
sb.add('page', pageTitle);
var request = getRequest(sb, 'pageView');
sendRequest(request, configTrackerPause);
// Send ping (to log that user has stayed on page)
var now = new Date();
if (configMinimumVisitTime && configHeartBeatTimer && !activityTrackingInstalled) {
activityTrackingInstalled = true;
// Capture our initial scroll points
resetMaxScrolls();
// Add event handlers; cross-browser compatibility here varies significantly
// @see http://quirksmode.org/dom/events
SnowPlow.addEventListener(SnowPlow.documentAlias, 'click', activityHandler);
SnowPlow.addEventListener(SnowPlow.documentAlias, 'mouseup', activityHandler);
SnowPlow.addEventListener(SnowPlow.documentAlias, 'mousedown', activityHandler);
SnowPlow.addEventListener(SnowPlow.documentAlias, 'mousemove', activityHandler);
SnowPlow.addEventListener(SnowPlow.documentAlias, 'mousewheel', activityHandler);
SnowPlow.addEventListener(SnowPlow.windowAlias, 'DOMMouseScroll', activityHandler);
SnowPlow.addEventListener(SnowPlow.windowAlias, 'scroll', scrollHandler); // Will updateMaxScrolls() for us
SnowPlow.addEventListener(SnowPlow.documentAlias, 'keypress', activityHandler);
SnowPlow.addEventListener(SnowPlow.documentAlias, 'keydown', activityHandler);
SnowPlow.addEventListener(SnowPlow.documentAlias, 'keyup', activityHandler);
SnowPlow.addEventListener(SnowPlow.windowAlias, 'resize', activityHandler);
SnowPlow.addEventListener(SnowPlow.windowAlias, 'focus', activityHandler);
SnowPlow.addEventListener(SnowPlow.windowAlias, 'blur', activityHandler);
// Periodic check for activity.
lastActivityTime = now.getTime();
setInterval(function heartBeat() {
var now = new Date();
// There was activity during the heart beat period;
// on average, this is going to overstate the visitDuration by configHeartBeatTimer/2
if ((lastActivityTime + configHeartBeatTimer) > now.getTime()) {
// Send ping if minimum visit time has elapsed
if (configMinimumVisitTime < now.getTime()) {
logPagePing(pageTitle); // Grab the min/max globals
}
}
}, configHeartBeatTimer);
}
}
/*
* Log that a user is still viewing a given page
* by sending a page ping.
* Not part of the public API - only called from
* logPageView() above.
*
* @param string pageTitle The page title to attach to this page ping
*/
function logPagePing(pageTitle) {
var sb = requestStringBuilder();
sb.add('e', 'pp'); // 'pp' for Page Ping
sb.add('page', pageTitle);
sb.addRaw('pp_mix', minXOffset); // Global
sb.addRaw('pp_max', maxXOffset); // Global
sb.addRaw('pp_miy', minYOffset); // Global
sb.addRaw('pp_may', maxYOffset); // Global
resetMaxScrolls();
var request = getRequest(sb, 'pagePing');
sendRequest(request, configTrackerPause);
}
/*
* Log the link or click with the server
*
* @param string url The target URL
* @param string linkType The type of link - link or download (see getLinkType() for details)
*/
// TODO: rename to LinkClick
// TODO: this functionality is not yet fully implemented.
// See https://github.com/snowplow/snowplow/issues/75
function logLink(url, linkType) {
var sb = requestStringBuilder();
sb.add('e', linkType);
sb.add('t_url', purify(url));
var request = getRequest(sb, 'link');
sendRequest(request, configTrackerPause);
}
/*
* Browser prefix
*/
function prefixPropertyName(prefix, propertyName) {
if (prefix !== '') {
return prefix + propertyName.charAt(0).toUpperCase() + propertyName.slice(1);
}
return propertyName;
}
/*
* Check for pre-rendered web pages, and log the page view/link
* according to the configuration and/or visibility
*
* @see http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html
*/
function trackCallback(callback) {
var isPreRendered,
i,
// Chrome 13, IE10, FF10
prefixes = ['', 'webkit', 'ms', 'moz'],
prefix;
if (!configCountPreRendered) {
for (i = 0; i < prefixes.length; i++) {
prefix = prefixes[i];
// does this browser support the page visibility API?
if (Object.prototype.hasOwnProperty.call(SnowPlow.documentAlias, prefixPropertyName(prefix, 'hidden'))) {
// if pre-rendered, then defer callback until page visibility changes
if (SnowPlow.documentAlias[prefixPropertyName(prefix, 'visibilityState')] === 'prerender') {
isPreRendered = true;
}
break;
}
}
}
if (isPreRendered) {
// note: the event name doesn't follow the same naming convention as vendor properties
SnowPlow.addEventListener(SnowPlow.documentAlias, prefix + 'visibilitychange', function ready() {
SnowPlow.documentAlias.removeEventListener(prefix + 'visibilitychange', ready, false);
callback();
});
return;
}
// configCountPreRendered === true || isPreRendered === false
callback();
}
/*
* Construct regular expression of classes
*/
function getClassesRegExp(configClasses, defaultClass) {
var i,
classesRegExp = '(^| )(piwik[_-]' + defaultClass;
if (configClasses) {
for (i = 0; i < configClasses.length; i++) {
classesRegExp += '|' + configClasses[i];
}
}
classesRegExp += ')( |$)';
return new RegExp(classesRegExp);
}
/*
* Link or Download?
*/
// TODO: why is a download assumed to always be on the same host?
// TODO: why return 0 if can't detect it as a link or download?
function getLinkType(className, href, isInLink) {
// outlinks
if (!isInLink) {
return 'lnk';
}
// does class indicate whether it is an (explicit/forced) outlink or a download?
var downloadPattern = getClassesRegExp(configDownloadClasses, 'download'),
linkPattern = getClassesRegExp(configLinkClasses, 'link'),
// does file extension indicate that it is a download?
downloadExtensionsPattern = new RegExp('\\.(' + configDownloadExtensions + ')([?&#]|$)', 'i');
return linkPattern.test(className) ? 'lnk' : (downloadPattern.test(className) || downloadExtensionsPattern.test(href) ? 'dl' : 0);
}
/*
* Process clicks
*/
function processClick(sourceElement) {