umami/tracker/index.js

199 lines
4.8 KiB
JavaScript
Raw Normal View History

2020-08-21 04:17:27 +02:00
(window => {
const {
screen: { width, height },
navigator: { language },
location,
2020-11-02 07:01:30 +01:00
localStorage,
document,
history,
} = window;
const { hostname, pathname, search } = location;
const { currentScript } = document;
if (!currentScript) return;
const delayDuration = 300;
const _data = 'data-';
const _false = 'false';
const attr = currentScript.getAttribute.bind(currentScript);
const website = attr(_data + 'website-id');
const hostUrl = attr(_data + 'host-url');
const autoTrack = attr(_data + 'auto-track') !== _false;
const dnt = attr(_data + 'do-not-track');
const domain = attr(_data + 'domains') || '';
const domains = domain.split(',').map(n => n.trim());
2020-09-01 05:25:31 +02:00
const root = hostUrl
2022-08-29 00:55:18 +02:00
? hostUrl.replace(/\/$/, '')
: currentScript.src.split('/').slice(0, -1).join('/');
const endpoint = `${root}/api/send`;
const screen = `${width}x${height}`;
2023-03-26 13:15:08 +02:00
const eventRegex = /data-umami-event-([\w-_]+)/;
2022-08-29 00:55:18 +02:00
2023-03-26 13:15:08 +02:00
/* Helper functions */
2023-03-26 13:15:08 +02:00
const hook = (_this, method, callback) => {
const orig = _this[method];
return (...args) => {
callback.apply(null, args);
return orig.apply(_this, args);
};
};
2023-03-03 19:38:14 +01:00
2023-03-26 13:15:08 +02:00
const getPath = url => {
if (url.substring(0, 4) === 'http') {
return '/' + url.split('/').splice(3).join('/');
}
return url;
};
2020-07-21 04:24:33 +02:00
2022-03-05 05:36:13 +01:00
const getPayload = () => ({
website,
hostname,
screen,
language,
2023-03-26 13:15:08 +02:00
title,
2022-03-05 05:36:13 +01:00
url: currentUrl,
2023-03-26 13:15:08 +02:00
referrer: currentRef,
2022-03-05 05:36:13 +01:00
});
2023-03-26 13:15:08 +02:00
/* Tracking functions */
2020-09-15 13:54:35 +02:00
2023-03-26 13:15:08 +02:00
const doNotTrack = () => {
const { doNotTrack, navigator, external } = window;
2020-09-16 12:07:22 +02:00
2023-03-26 13:15:08 +02:00
const msTrackProtection = 'msTrackingProtectionEnabled';
const msTracking = () => {
return external && msTrackProtection in external && external[msTrackProtection]();
};
2022-01-15 04:10:46 +01:00
2023-03-26 13:15:08 +02:00
const dnt = doNotTrack || navigator.doNotTrack || navigator.msDoNotTrack || msTracking();
return dnt == '1' || dnt === 'yes';
2020-09-18 22:40:46 +02:00
};
2023-03-26 13:15:08 +02:00
const trackingDisabled = () =>
(localStorage && localStorage.getItem('umami.disabled')) ||
(dnt && doNotTrack()) ||
(domain && !domains.includes(hostname));
2020-09-16 12:07:22 +02:00
const handlePush = (state, title, url) => {
2021-02-02 07:49:00 +01:00
if (!url) return;
currentRef = currentUrl;
2023-03-26 13:15:08 +02:00
currentUrl = getPath(url.toString());
2021-02-02 07:49:00 +01:00
if (currentUrl !== currentRef) {
2023-03-26 13:15:08 +02:00
setTimeout(track, delayDuration);
2020-09-16 12:07:22 +02:00
}
2020-09-15 13:54:35 +02:00
};
2023-03-26 13:15:08 +02:00
const handleClick = () => {
const callback = e => {
const t = e.target;
const attr = t.getAttribute.bind(t);
const eventName = attr(_data + 'umami-event');
if (eventName) {
const eventData = {};
t.getAttributeNames().forEach(name => {
const match = name.match(eventRegex);
if (match) {
eventData[match[1]] = attr(name);
}
});
if (t.tagName === 'A') {
const href = attr('href');
const target = attr('target');
if (
href &&
target !== '_blank' &&
!(e.ctrlKey || e.shiftKey || e.metaKey || (e.button && e.button === 1))
) {
e.preventDefault();
2023-03-31 14:55:28 +02:00
return track(eventName, { data: eventData }).then(() => {
2023-03-26 13:15:08 +02:00
location.href = href;
});
}
}
track(eventName, { data: eventData });
}
};
2023-03-26 13:15:08 +02:00
document.addEventListener('click', callback, true);
};
const observeTitle = () => {
2023-03-26 13:15:08 +02:00
const callback = ([entry]) => {
2023-03-31 08:13:03 +02:00
title = entry.target.text;
};
2023-03-26 13:15:08 +02:00
const observer = new MutationObserver(callback);
observer.observe(document.querySelector('head > title'), {
subtree: true,
characterData: true,
2023-03-31 08:13:03 +02:00
childList: true,
});
};
2023-03-26 13:15:08 +02:00
const send = payload => {
if (trackingDisabled()) return;
2020-09-16 12:07:22 +02:00
2023-03-26 13:15:08 +02:00
return fetch(endpoint, {
method: 'POST',
body: JSON.stringify({ type: 'event', payload }),
headers: { 'Content-Type': 'application/json', ['x-umami-cache']: cache },
})
.then(res => res.text())
.then(text => (cache = text));
};
2020-07-19 10:57:01 +02:00
2023-03-26 13:15:08 +02:00
const track = (name = {}, data = {}) => {
if (typeof name === 'string') {
return send({ ...getPayload(), ...data, name });
} else if (typeof name === 'object') {
return send({ ...getPayload(), ...name });
}
return Promise.reject();
};
/* Start */
2020-09-18 22:40:46 +02:00
2023-03-26 13:15:08 +02:00
if (!window.umami) {
window.umami = {
track,
};
}
let currentUrl = `${pathname}${search}`;
let currentRef = getPath(document.referrer);
let title = document.title;
let cache;
let initialized;
if (autoTrack && !trackingDisabled()) {
2020-09-18 22:40:46 +02:00
history.pushState = hook(history, 'pushState', handlePush);
history.replaceState = hook(history, 'replaceState', handlePush);
2023-03-26 13:15:08 +02:00
handleClick();
observeTitle();
2020-09-18 22:40:46 +02:00
2023-03-26 13:15:08 +02:00
const init = () => {
if (document.readyState === 'complete' && !initialized) {
track();
initialized = true;
}
};
2022-03-05 05:36:13 +01:00
2023-03-26 13:15:08 +02:00
document.addEventListener('readystatechange', init, true);
2022-03-05 05:36:13 +01:00
2023-03-26 13:15:08 +02:00
init();
2020-09-03 17:53:39 +02:00
}
2020-08-21 04:17:27 +02:00
})(window);