/
default.js
491 lines (426 loc) · 14.3 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
/* eslint-env browser */
(function(
window,
baseUrl,
apiUrlPrefix,
apiUrlSuffix,
onlineUrlPrefix,
onlineUrlSuffix,
version
) {
if (!window) return;
var https = "https:";
var protocol = https + "//";
// Generate the needed URLs, this seems like a lot of repetition, but it
// makes our script availble for multple destination which prevents us to
// need multiple scripts. The minified version stays small.
var fullApiUrl = protocol + apiUrlPrefix + baseUrl + apiUrlSuffix;
var fullErrorUrl = protocol + apiUrlPrefix + baseUrl;
/** if online **/
var fullOnlineUrl = protocol + onlineUrlPrefix + baseUrl + onlineUrlSuffix;
/** endif **/
// Set urls outside try block because they are needed in the catch block
var con = window.console;
var doNotTrack = "doNotTrack";
var pageviews = "pageviews";
var events = "events";
var slash = "/";
var nav = window.navigator;
var userAgent = nav.userAgent;
var loc = window.location;
var doc = window.document;
var locationHostname = loc.hostname;
var notSending = "Not sending requests ";
var localhost = "localhost";
var contentTypeText = "Content-Type";
var nullVar = null;
var encodeURIComponentFunc = encodeURIComponent;
// We use content type text/plain here because we don't want to send an
// pre-flight OPTIONS request
var contentTypeTextPlain = "text/plain; charset=UTF-8";
var thousand = 1000;
var addEventListenerFunc = window.addEventListener;
// 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);
};
// Send error via image so we bypass failing XHR requests
function sendError(errorOrMessage) {
errorOrMessage = errorOrMessage.message || errorOrMessage;
warn(errorOrMessage);
new Image().src =
fullErrorUrl +
"/error.gif" +
"?error=" +
encodeURIComponentFunc(errorOrMessage) +
"&url=" +
encodeURIComponentFunc(locationHostname + loc.pathname);
}
// We listen for the error events and only send errors that are
// from our script (checked by filename) to our server.
addEventListenerFunc(
"error",
function(event) {
if (event.filename && event.filename.indexOf(baseUrl) > -1) {
sendError(event.message);
}
},
false
);
/** if spa **/
var pushState = "pushState";
var dis = window.dispatchEvent;
/** endif **/
/** if duration **/
var duration = "duration";
var start = Date.now();
/** endif **/
/** if scroll **/
var scrolled = 0;
/** endif **/
var scriptElement = doc.querySelector('script[src*="' + baseUrl + '"]');
var attr = function(scriptElement, attribute) {
return scriptElement && scriptElement.getAttribute("data-" + attribute);
};
var mode = attr(scriptElement, "mode");
var skipDNT = attr(scriptElement, "skip-dnt") === "true";
var functionName = attr(scriptElement, "sa-global") || "sa";
// Don't track when Do Not Track is set to true
if (!skipDNT && doNotTrack in nav && nav[doNotTrack] === "1")
return warn(notSending + "when " + doNotTrack + " is enabled");
// Don't track when localhost
if (locationHostname === localhost || loc.protocol === "file:")
return warn(notSending + "from " + localhost);
// We do advanced bot detection in our API, but this line filters already most bots
if (!userAgent || userAgent.search(/(bot|spider|crawl)/gi) > -1)
return warn(notSending + "because bot detected");
try {
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];
};
// This code could error on not having resolvedOptions in the Android Webview, that's why we use try...catch
var timezone;
try {
timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
} catch (e) {
/* Do nothing */
}
// We don't want to end up with sensitive data so we clean the referrer URL
var utmRegexPrefix = "(utm_)?";
var payload = {
version: version,
hostname: locationHostname,
https: loc.protocol === https,
timezone: timezone,
width: window.innerWidth,
source: {
source: getParams(utmRegexPrefix + "source|source|ref"),
medium: getParams(utmRegexPrefix + "medium"),
campaign: getParams(utmRegexPrefix + "campaign"),
referrer:
(doc.referrer || "")
.replace(
/^https?:\/\/((m|l|w{2,3}([0-9]+)?)\.)?([^?#]+)(.*)$/,
"$4"
)
.replace(/^([^/]+)\/$/, "$1") || nullVar
},
pageviews: []
};
// We don't put msHidden in if duration block, because it's used outside of that functionality
var msHidden = 0;
/** if duration **/
var hiddenStart = nullVar;
window.addEventListener(
"visibilitychange",
function() {
if (doc.hidden) hiddenStart = Date.now();
else msHidden += Date.now() - hiddenStart;
},
false
);
/** endif **/
var seconds = function(since) {
return Math.round((Date.now() - (since || 0)) / thousand);
};
var sendBeacon = "sendBeacon";
var stringify = JSON.stringify;
var lastSendPath;
// Safari on iOS < 13 has some issues with the Beacon API
var useSendBeacon =
sendBeacon in nav &&
/ip(hone|ad)(.*)os\s([1-9]|1[0-2])_/i.test(userAgent) === false;
if (useSendBeacon)
addEventListenerFunc(
"unload",
function() {
try {
var last = payload[pageviews][payload[pageviews].length - 1];
/** if duration **/
last[duration] = seconds(start + msHidden);
msHidden = 0;
/** endif **/
/** if scroll **/
var currentScroll = Math.max(0, scrolled, position());
if (currentScroll) last.scrolled = currentScroll;
/** endif **/
payload.time = seconds();
nav[sendBeacon](fullApiUrl, stringify(payload));
} catch (error) {
sendError(error);
}
},
false
);
/** if scroll **/
var scroll = "scroll";
var body = doc.body || {};
var documentElement = doc.documentElement || {};
var position = function() {
try {
var Height = "Height";
var scrollHeight = scroll + Height;
var offsetHeight = "offset" + Height;
var clientHeight = "client" + Height;
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) {
sendError(error);
return 0;
}
};
addEventListenerFunc("load", function() {
scrolled = position();
addEventListenerFunc(
scroll,
function() {
if (scrolled < position()) scrolled = position();
},
false
);
});
/** endif **/
var post = function(type, data, deleteSourceInfo) {
try {
var event;
var payloadPageviews = payload[pageviews];
var payloadPageviewsLength = payloadPageviews
? payloadPageviews.length
: 0;
var payloadPageviewLast = payloadPageviewsLength
? payloadPageviews[payloadPageviewsLength - 1]
: nullVar;
if (type === events) {
/** if events **/
try {
event = "" + (data instanceof Function ? data() : data);
} catch (error) {
warn("in your event function: " + error.message);
event = "event_errored";
}
if (payloadPageviewLast) {
if (payloadPageviewLast[events])
payloadPageviewLast[events].push(event);
else payloadPageviewLast[events] = [event];
} else if (useSendBeacon) {
warn("Couldn't save event '" + event + "'");
}
if (useSendBeacon) return;
else {
delete payload[pageviews];
payload[events] = [event];
}
/** endif **/
} else {
// Continue when type is pageviews
if (payloadPageviewsLength) {
/** if duration **/
payloadPageviewLast.duration = seconds(start + msHidden);
/** endif **/
/** if scroll **/
payloadPageviewLast.scrolled = scrolled;
/** endif **/
}
if (payload[pageviews]) payload[pageviews].push(data);
else payload[pageviews] = [data];
// Delete source when refreshing the page and only when it's the first page view.
// It's zero here because the length is retrieved before adding it to the array.
if (deleteSourceInfo && payloadPageviewsLength === 0) {
delete payload.source;
}
/** if online **/
try {
var requestCounter = new XMLHttpRequest();
// fullOnlineUrl || fullOnlineUrl is a hack to make the minifier believe
// this variable is used multiple times. It does not result in extra
// bytes.
requestCounter.open("POST", fullOnlineUrl || fullOnlineUrl, true);
requestCounter.setRequestHeader(
contentTypeText,
contentTypeTextPlain
);
requestCounter.send(stringify(payload));
} catch (error) {
// Do nothing
}
/** endif **/
if (useSendBeacon) {
/** if duration **/
start = Date.now();
msHidden = 0;
/** endif **/
/** if scroll **/
scrolled = window.setTimeout(position, 500);
/** endif **/
return;
}
}
if (deleteSourceInfo) {
delete payload.source;
}
var request = new XMLHttpRequest();
request.open("POST", fullApiUrl, true);
payload.time = seconds();
request.setRequestHeader(contentTypeText, contentTypeTextPlain);
request.send(stringify(payload));
delete payload[pageviews];
delete payload[events];
} catch (error) {
sendError(error);
}
};
var pageview = function(isPushState) {
// Obfuscate personal data in URL by dropping the search and hash
var path = loc.pathname;
/** 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 **/
// Don't send the last path again (this could happen when pushState is used to change the path hash or search)
if (lastSendPath === path) return;
lastSendPath = path;
var data = {
path: path,
added: seconds()
};
// 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;
/** if uniques **/
// We set unique variable based on pushstate or back navigation, if no match we check the referrer
data.unique =
isPushState || userNavigated
? false
: doc.referrer
? doc.referrer.split(slash)[2] !== locationHostname
: true;
/** endif **/
post(pageviews, data, isPushState || userNavigated);
};
/** if spa **/
var his = window.history;
var hisPushState = his ? his.pushState : nullVar;
if (hisPushState && Event && dis) {
var stateListener = function(type) {
var orig = his[type];
return function() {
var rv = orig.apply(this, arguments);
var event = new Event(type);
event.arguments = arguments;
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 (mode === "hash" && "onhashchange" in window) {
addEventListenerFunc(
"hashchange",
function() {
pageview(1);
},
false
);
}
/** endif **/
pageview();
/** if events **/
var defaultEventFunc = function(event) {
post(events, event);
};
// 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) post(events, queue[event]);
/** endif **/
} catch (e) {
sendError(e);
}
})(
window,
"{{baseUrl}}",
"{{apiUrlPrefix}}",
"{{apiUrlSuffix}}",
"{{onlineUrlPrefix}}",
"{{onlineUrlSuffix}}",
"{{version}}"
);