/
default.js
794 lines (686 loc) · 21.8 KB
/
default.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
/* eslint-env browser */
(function (window, overwriteOptions, baseUrl, apiUrlPrefix, version, saGlobal) {
try {
// Only load our script once, customers can still send multiple page views
// with the sa_pageview function if they turn off auto collect.
var loadedVariable = saGlobal + "_loaded";
if (!window || window[loadedVariable] === true) return;
window[loadedVariable] = true;
/////////////////////
// PREDEFINED VARIABLES FOR BETTER MINIFICATION
//
// This seems like a lot of repetition, but it makes our script available for
// multple destination which prevents us to need multiple scripts. The minified
// version stays small.
var https = "https:";
var pageviewsText = "pageview";
/** if errorhandling **/
var errorText = "error";
/** endif **/
var slash = "/";
var protocol = https + "//";
var con = window.console;
var doNotTrack = "doNotTrack";
var nav = window.navigator;
var loc = window.location;
var locationHostname = loc.hostname;
var doc = window.document;
var userAgent = nav.userAgent;
var notSending = "Not sending request ";
var fetchedHighEntropyValues = false;
var encodeURIComponentFunc = encodeURIComponent;
var decodeURIComponentFunc = decodeURIComponent;
var stringify = JSON.stringify;
var thousand = 1000;
var addEventListenerFunc = window.addEventListener;
var fullApiUrl = protocol + apiUrlPrefix + baseUrl;
var undefinedVar = undefined;
var documentElement = doc.documentElement || {};
var language = "language";
var Height = "Height";
var Width = "Width";
var scroll = "scroll";
var trueText = "true";
var uaData = nav.userAgentData;
var scrollHeight = scroll + Height;
var offsetHeight = "offset" + Height;
var clientHeight = "client" + Height;
var clientWidth = "client" + Width;
var pagehide = "pagehide";
var platformText = "platform";
var platformVersionText = "platformVersion";
var isBotAgent =
/(bot|spider|crawl)/i.test(userAgent) && !/(cubot)/i.test(userAgent);
/** if screen **/
var screen = window.screen;
/** endif **/
/////////////////////
// PAYLOAD FOR BOTH PAGE VIEWS AND EVENTS
//
/** if botdetection **/
var bot =
nav.webdriver ||
window.__nightmare ||
"callPhantom" in window ||
"_phantom" in window ||
"phantom" in window ||
isBotAgent;
/** else **/
var bot = isBotAgent;
/** endif **/
var payload = {
version: version,
ua: userAgent,
};
if (bot) payload.bot = true;
/** if sri **/
payload.sri = true;
/** endif **/
// Use User-Agent Client Hints for better privacy
// https://web.dev/user-agent-client-hints/
if (uaData) {
payload.mobile = uaData.mobile;
payload.brands = stringify(uaData.brands);
}
/////////////////////
// HELPER FUNCTIONS
//
// A simple log function so the user knows why a request is not being send
var warn = function (message) {
if (con && con.warn) con.warn("Simple Analytics:", message);
};
var now = Date.now;
var uuid = function () {
var cryptoObject = window.crypto || window.msCrypto;
var emptyUUID = [1e7] + -1e3 + -4e3 + -8e3 + -1e11;
var uuidRegex = /[018]/g;
try {
return emptyUUID.replace(uuidRegex, function (c) {
return (
c ^
(cryptoObject.getRandomValues(new Uint8Array(1))[0] &
(15 >> (c / 4)))
).toString(16);
});
} catch (error) {
return emptyUUID.replace(uuidRegex, function (c) {
var r = (Math.random() * 16) | 0,
v = c < 2 ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
};
var isFunction = function (func) {
return typeof func == "function";
};
var isString = function (string) {
return typeof string == "string";
};
var assign = function () {
var to = {};
var arg = arguments;
for (var index = 0; index < arg.length; index++) {
var nextSource = arg[index];
if (nextSource) {
for (var nextKey in nextSource) {
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
};
var isBoolean = function (value) {
return !!value === value;
};
var getParams = function (regex) {
// From the search we grab the utm_source and ref and save only that
var matches = loc.search.match(
new RegExp("[?&](" + regex + ")=([^?&]+)", "gi")
);
var match = matches
? matches.map(function (m) {
return m.split("=")[1];
})
: [];
if (match && match[0]) return match[0];
};
/** if ignorepages **/
// Ignore pages specified in data-ignore-pages
var shouldIgnore = function (path) {
for (var i in ignorePages) {
var ignorePageRaw = ignorePages[i];
if (!ignorePageRaw) continue;
// Prepend a slash when it's missing
var ignorePage =
ignorePageRaw[0] == slash ? ignorePageRaw : slash + ignorePageRaw;
try {
if (
ignorePage === path ||
new RegExp(ignorePage.replace(/\*/gi, "(.*)"), "gi").test(path)
)
return true;
} catch (error) {
return false;
}
}
return false;
};
/** endif **/
/////////////////////
// SEND DATA VIA OUR PIXEL
//
// Send data via image
var sendData = function (data, callback) {
data = assign(payload, data);
var image = new Image();
/** if events **/
if (callback) {
image.onerror = callback;
image.onload = callback;
}
/** endif **/
image.src =
fullApiUrl +
"/simple.gif?" +
Object.keys(data)
.filter(function (key) {
return data[key] != undefinedVar;
})
.map(function (key) {
return (
encodeURIComponentFunc(key) +
"=" +
encodeURIComponentFunc(data[key])
);
})
.join("&") +
"&time=" +
Date.now();
};
/** if errorhandling **/
/////////////////////
// ERROR FUNCTIONS
//
// Send errors
var sendError = function (errorOrMessage) {
errorOrMessage = errorOrMessage.message || errorOrMessage;
warn(errorOrMessage);
sendData({
type: errorText,
error: errorOrMessage,
url: definedHostname + loc.pathname,
});
};
// We listen for the error events and only send errors that are
// from our script (checked by filename) to our server.
addEventListenerFunc(
errorText,
function (event) {
if (event.filename && event.filename.indexOf(baseUrl) > -1) {
sendError(event.message);
}
},
false
);
/** endif **/
/////////////////////
// INITIALIZE VALUES
//
/** if spa **/
var pushState = "pushState";
var dis = window.dispatchEvent;
/** endif **/
/** if duration **/
var duration = "duration";
var start = now();
/** endif **/
/** if scroll **/
var scrolled = 0;
/** endif **/
// This code could error on (incomplete) implementations, that's why we use try...catch
var timezone;
try {
timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
} catch (e) {
/* Do nothing */
}
/////////////////////
// GET SETTINGS
//
// Find the script element where options can be set on
var scriptElement = doc.querySelector('script[src*="' + baseUrl + '"]');
var attr = function (scriptElement, attribute) {
return scriptElement && scriptElement.getAttribute("data-" + attribute);
};
// Script mode, this can be hash mode for example
var mode = overwriteOptions.mode || attr(scriptElement, "mode");
/** if ignorednt **/
// Should we record Do Not Track visits?
var collectDnt = isBoolean(overwriteOptions.collectDnt)
? overwriteOptions.collectDnt
: attr(scriptElement, "ignore-dnt") == trueText ||
attr(scriptElement, "skip-dnt") == trueText ||
attr(scriptElement, "collect-dnt") == trueText;
/** endif **/
// Customers can overwrite their hostname, here we check for that
var definedHostname =
overwriteOptions.hostname ||
attr(scriptElement, "hostname") ||
locationHostname;
/** if (or spa hash) **/
// Some customers want to collect page views manually
var autoCollect = !(
attr(scriptElement, "auto-collect") == "false" ||
overwriteOptions.autoCollect === false
);
/** endif **/
/** if events **/
// Event function name
var functionName =
overwriteOptions.saGlobal || attr(scriptElement, "sa-global") || saGlobal;
/** endif **/
/** if ignorepages **/
// Customers can ignore certain pages
var ignorePagesRaw =
overwriteOptions.ignorePages || attr(scriptElement, "ignore-pages");
// Make sure ignore pages is an array
var ignorePages = Array.isArray(ignorePagesRaw)
? ignorePagesRaw
: isString(ignorePagesRaw) && ignorePagesRaw.length
? ignorePagesRaw.split(/, ?/)
: [];
/** endif **/
/////////////////////
// ADD HOSTNAME TO PAYLOAD
//
payload.hostname = definedHostname;
/////////////////////
// ADD WARNINGS
//
/** if warnings **/
// Warn when no document.doctype is defined (this breaks some documentElement dimensions)
if (!doc.doctype) warn("Add DOCTYPE html for more accurate dimensions");
/** endif **/
// When a customer overwrites the hostname, we need to know what the original
// hostname was to hide that domain from referrer traffic
if (definedHostname !== locationHostname)
payload.hostname_original = locationHostname;
// Don't track when Do Not Track is set to true
/** if ignorednt **/
if (!collectDnt && doNotTrack in nav && nav[doNotTrack] == "1")
return warn(notSending + "when " + doNotTrack + " is enabled");
/** else **/
if (doNotTrack in nav && nav[doNotTrack] == "1")
return warn(notSending + "when " + doNotTrack + " is enabled");
/** endif **/
/** unless testing **/
// Don't track when localhost or when it's an IP address
if (
locationHostname.indexOf(".") == -1 ||
/^[0-9]+$/.test(locationHostname.replace(/\./g, ""))
)
return warn(notSending + "from " + locationHostname);
/** endunless **/
/////////////////////
// SETUP INITIAL VARIABLES
//
var page = {};
var lastPageId = uuid();
var lastSendPath;
// We don't want to end up with sensitive data so we clean the referrer URL
var referrer =
(doc.referrer || "")
.replace(locationHostname, definedHostname)
.replace(/^https?:\/\/((m|l|w{2,3}([0-9]+)?)\.)?([^?#]+)(.*)$/, "$4")
.replace(/^([^/]+)$/, "$1") || undefinedVar;
// The prefix utm_ is optional
var utmRegexPrefix = "(utm_)?";
var source = {
source: getParams(utmRegexPrefix + "source|ref"),
medium: getParams(utmRegexPrefix + "medium"),
campaign: getParams(utmRegexPrefix + "campaign"),
term: getParams(utmRegexPrefix + "term"),
content: getParams(utmRegexPrefix + "content"),
referrer: referrer,
};
/////////////////////
// TIME ON PAGE AND SCROLLED LOGIC
//
// We don't put msHidden in if duration block, because it's used outside of that functionality
var msHidden = 0;
var sendBeaconText = "sendBeacon";
var sendOnLeave = function (id, push) {
var append = { type: "append", original_id: push ? id : lastPageId };
/** if duration **/
append[duration] = Math.round((now() - start - msHidden) / thousand);
msHidden = 0;
start = now();
/** endif **/
/** if scroll **/
append.scrolled = Math.max(0, scrolled, position());
/** endif **/
if (push || !(sendBeaconText in nav)) {
sendData(append);
} else {
nav[sendBeaconText](
fullApiUrl + "/append",
stringify(assign(payload, append))
);
}
};
/** if duration **/
var hiddenStart;
window.addEventListener(
"visibilitychange",
function () {
if (doc.hidden) {
if (!("on" + pagehide in window)) sendOnLeave();
hiddenStart = now();
} else msHidden += now() - hiddenStart;
},
false
);
/** endif **/
addEventListenerFunc(pagehide, sendOnLeave, false);
/** if scroll **/
var body = doc.body || {};
var position = function () {
try {
var documentClientHeight = documentElement[clientHeight] || 0;
var height = Math.max(
body[scrollHeight] || 0,
body[offsetHeight] || 0,
documentElement[clientHeight] || 0,
documentElement[scrollHeight] || 0,
documentElement[offsetHeight] || 0
);
return Math.min(
100,
Math.round(
(100 * ((documentElement.scrollTop || 0) + documentClientHeight)) /
height /
5
) * 5
);
} catch (error) {
return 0;
}
};
addEventListenerFunc("load", function () {
scrolled = position();
addEventListenerFunc(
scroll,
function () {
if (scrolled < position()) scrolled = position();
},
false
);
});
/** endif **/
/////////////////////
// ACTUAL PAGE VIEW LOGIC
//
var getPath = function (overwrite) {
var path = "";
// decodeURIComponent can fail when having invalid characters
// https://github.com/simpleanalytics/roadmap/issues/462
try {
path = overwrite || decodeURIComponentFunc(loc.pathname);
} catch (e) {
// Do nothing
}
/** if ignorepages **/
// Ignore pages specified in data-ignore-pages
if (shouldIgnore(path)) {
warn(notSending + "because " + path + " is ignored");
return;
}
/** endif **/
/** if hash **/
// Add hash to path when script is put in to hash mode
if (mode == "hash" && loc.hash) path += loc.hash.split("?")[0];
/** endif **/
return path;
};
// Send page view and append data to it
var sendPageView = function (isPushState, deleteSourceInfo, sameSite) {
if (isPushState) sendOnLeave("" + lastPageId, true);
lastPageId = uuid();
page.id = lastPageId;
var currentPage = definedHostname + getPath();
sendData(
assign(
page,
deleteSourceInfo
? {
referrer: sameSite ? referrer : null,
}
: source,
{
https: loc.protocol == https,
timezone: timezone,
type: pageviewsText,
}
)
);
referrer = currentPage;
};
var pageview = function (isPushState, pathOverwrite) {
// Obfuscate personal data in URL by dropping the search and hash
var path = getPath(pathOverwrite);
// Don't send the last path again (this could happen when pushState is used to change the path hash or search)
if (!path || lastSendPath == path) return;
lastSendPath = path;
/** if screen **/
var data = {
path: path,
viewport_width:
Math.max(documentElement[clientWidth] || 0, window.innerWidth || 0) ||
null,
viewport_height:
Math.max(
documentElement[clientHeight] || 0,
window.innerHeight || 0
) || null,
};
/** else **/
var data = {
path: path,
};
/** endif **/
if (nav[language]) data[language] = nav[language];
/** if screen **/
if (screen) {
data.screen_width = screen.width;
data.screen_height = screen.height;
}
/** endif **/
// If a user does refresh we need to delete the referrer because otherwise it count double
var perf = window.performance;
var navigation = "navigation";
// Check if back, forward or reload buttons are being used in modern browsers
var userNavigated =
perf &&
perf.getEntriesByType &&
perf.getEntriesByType(navigation)[0] &&
perf.getEntriesByType(navigation)[0].type
? ["reload", "back_forward"].indexOf(
perf.getEntriesByType(navigation)[0].type
) > -1
: // Check if back, forward or reload buttons are being use in older browsers
// 1: TYPE_RELOAD, 2: TYPE_BACK_FORWARD
perf &&
perf[navigation] &&
[1, 2].indexOf(perf[navigation].type) > -1;
// Check if referrer is the same as current real hostname (not the defined hostname!)
var sameSite = referrer
? doc.referrer.split(slash)[2] == locationHostname
: false;
/** if uniques **/
// We set unique variable based on pushstate or back navigation, if no match we check the referrer
data.unique = isPushState || userNavigated ? false : !sameSite;
/** endif **/
page = data;
var triggerSendPageView = function () {
fetchedHighEntropyValues = true;
sendPageView(isPushState, isPushState || userNavigated, sameSite);
};
if (!fetchedHighEntropyValues) {
// Request platform information if this is available
try {
if (uaData && isFunction(uaData.getHighEntropyValues)) {
uaData
.getHighEntropyValues([platformText, platformVersionText])
.then(function (highEntropyValues) {
payload.os_name = highEntropyValues[platformText];
payload.os_version = highEntropyValues[platformVersionText];
triggerSendPageView();
})
.catch(triggerSendPageView);
} else {
triggerSendPageView();
}
} catch (e) {
triggerSendPageView();
}
} else {
triggerSendPageView();
}
};
/** if spa **/
/////////////////////
// AUTOMATED PAGE VIEW COLLECTION
//
var his = window.history;
var hisPushState = his ? his.pushState : undefinedVar;
// Overwrite history pushState function to
// allow listening on the pushState event
if (autoCollect && hisPushState && Event && dis) {
var stateListener = function (type) {
var orig = his[type];
return function () {
var arg = arguments;
var rv = orig.apply(this, arg);
var event;
if (typeof Event == "function") {
event = new Event(type);
} else {
// Fix for IE
event = doc.createEvent("Event");
event.initEvent(type, true, true);
}
event.arguments = arg;
dis(event);
return rv;
};
};
his.pushState = stateListener(pushState);
addEventListenerFunc(
pushState,
function () {
pageview(1);
},
false
);
addEventListenerFunc(
"popstate",
function () {
pageview(1);
},
false
);
}
/** endif **/
/** if hash **/
// When in hash mode, we record a pageview based on the onhashchange function
if (autoCollect && mode == "hash" && "onhashchange" in window) {
addEventListenerFunc(
"hashchange",
function () {
pageview(1);
},
false
);
}
/** endif **/
/** if (or spa hash) **/
if (autoCollect) pageview();
else
window.sa_pageview = function (path) {
pageview(0, path);
};
/** else **/
pageview();
/** endif **/
/** if events **/
/////////////////////
// EVENTS
//
var sessionId = uuid();
var validTypes = ["string", "number"];
var sendEvent = function (event, callbackRaw) {
var eventIsFunction = isFunction(event);
var callback = isFunction(callbackRaw) ? callbackRaw : function () {};
if (validTypes.indexOf(typeof event) < 0 && !eventIsFunction) {
warn("event is not a string: " + event);
return callback();
}
try {
if (eventIsFunction) {
event = event();
if (validTypes.indexOf(typeof event) < 0) {
warn("event function output is not a string: " + event);
return callback();
}
}
} catch (error) {
warn("in your event function: " + error.message);
return callback();
}
event = ("" + event).replace(/[^a-z0-9]+/gi, "_").replace(/(^_|_$)/g, "");
if (event) {
sendData(
assign(source, bot ? { bot: true } : {}, {
type: "event",
event: event,
page_id: page.id,
session_id: sessionId,
}),
callback
);
}
};
var defaultEventFunc = function (event, callback) {
sendEvent(event, callback);
};
// Set default function if user didn't define a function
if (!window[functionName]) window[functionName] = defaultEventFunc;
var eventFunc = window[functionName];
// Read queue of the user defined function
var queue = eventFunc && eventFunc.q ? eventFunc.q : [];
// Overwrite user defined function
window[functionName] = defaultEventFunc;
// Post events from the queue of the user defined function
for (var event in queue) {
Array.isArray(queue[event])
? sendEvent.apply(null, queue[event])
: sendEvent(queue[event]);
}
/** endif **/
} catch (e) {
/** if errorhandling **/
sendError(e);
/** else **/
warn(e);
/** endif **/
}
})(
window,
"{{overwriteOptions}}",
"{{baseUrl}}",
"{{apiUrlPrefix}}",
"{{scriptName}}",
"{{saGlobal}}"
);