simplify tracker to not depend on modules, we want this file as small as possible anyway. prevents #124

This commit is contained in:
Danny van Kooten 2018-09-14 10:25:21 +02:00
parent 86e50ca573
commit b75506ce8f
1 changed files with 51 additions and 8 deletions

View File

@ -1,8 +1,5 @@
'use strict';
import * as cookies from 'cookies-js';
import * as util from './lib/util.js';
let queue = window.fathom.q || [];
let trackerUrl = '';
@ -11,6 +8,53 @@ const commands = {
"setTrackerUrl": setTrackerUrl,
};
// convert object to query string
function stringifyObject(obj) {
var keys = Object.keys(obj);
return '?' +
keys.map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(obj[k]);
}).join('&');
}
function randomString(n) {
var s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return Array(n).join().split(',').map(() => s.charAt(Math.floor(Math.random() * s.length))).join('');
}
function getCookie(name) {
var cookies = document.cookie ? document.cookie.split('; ') : [];
for (var i = 0; i < cookies.length; i++) {
var parts = cookies[i].split('=');
if (decodeURIComponent(parts[0]) !== name) {
continue;
}
var cookie = parts.slice(1).join('=');
return decodeURIComponent(cookie);
}
return '';
}
function setCookie(name, data, args) {
name = encodeURIComponent(name);
data = encodeURIComponent(String(data));
var str = name + '=' + data;
if(args.path) {
str += ';path=' + args.path;
}
if (args.expires) {
str += ';expires='+args.expires.toUTCString();
}
document.cookie = str;
}
function newVisitorData() {
return {
isNewVisitor: true,
@ -25,7 +69,7 @@ function getData() {
let thirtyMinsAgo = new Date();
thirtyMinsAgo.setMinutes(thirtyMinsAgo.getMinutes() - 30);
let data = cookies.get('_fathom');
let data = getCookie('_fathom');
if(! data) {
return newVisitorData();
}
@ -97,7 +141,7 @@ function trackPageview() {
let data = getData();
const d = {
id: util.randomString(20),
id: randomString(20),
pid: data.previousPageviewId || '',
p: path,
h: hostname,
@ -108,11 +152,10 @@ function trackPageview() {
};
let i = document.createElement('img');
i.src = trackerUrl + util.stringifyObject(d);
i.src = trackerUrl + stringifyObject(d);
i.addEventListener('load', function() {
let now = new Date();
let midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 24, 0, 0);
let expires = Math.round((midnight - now) / 1000);
// update data in cookie
if( data.pagesViewed.indexOf(path) == -1 ) {
@ -122,7 +165,7 @@ function trackPageview() {
data.isNewVisitor = false;
data.isNewSession = false;
data.lastSeen = +new Date();
cookies.set('_fathom', JSON.stringify(data), { 'expires': expires });
setCookie('_fathom', JSON.stringify(data), { expires: midnight, path: '/' });
});
document.body.appendChild(i);
window.setTimeout(() => { document.body.removeChild(i)}, 1000);