umami/tracker/index.js

211 lines
4.9 KiB
JavaScript
Raw Normal View History

2022-02-16 05:58:17 +01:00
import { doNotTrack, hook } from '../lib/web';
import { removeTrailingSlash } from '../lib/url';
2020-07-18 04:15:29 +02:00
2020-08-21 04:17:27 +02:00
(window => {
const {
screen: { width, height },
navigator: { language },
location: { hostname, pathname, search },
2020-11-02 07:01:30 +01:00
localStorage,
2020-10-03 05:33:46 +02:00
sessionStorage,
document,
history,
} = window;
const script = document.querySelector('script[data-website-id]');
2020-08-21 04:17:27 +02:00
if (!script) return;
const attr = script.getAttribute.bind(script);
2020-09-18 22:40:46 +02:00
const website = attr('data-website-id');
const hostUrl = attr('data-host-url');
const autoTrack = attr('data-auto-track') !== 'false';
2020-10-03 05:33:46 +02:00
const dnt = attr('data-do-not-track');
const useCache = attr('data-cache');
const domain = attr('data-domains') || '';
const domains = domain.split(',').map(n => n.trim());
2020-09-18 22:40:46 +02:00
const eventClass = /^umami--([a-z]+)--([\w]+[\w-]*)$/;
const eventSelect = "[class*='umami--']";
const cacheKey = 'umami.cache';
const disableTracking = () =>
(localStorage && localStorage.getItem('umami.disabled')) ||
2020-10-05 07:27:59 +02:00
(dnt && doNotTrack()) ||
(domain && !domains.includes(hostname));
2020-08-21 04:17:27 +02:00
2020-09-01 05:25:31 +02:00
const root = hostUrl
? removeTrailingSlash(hostUrl)
2020-12-05 07:41:30 +01:00
: script.src.split('/').slice(0, -1).join('/');
const screen = `${width}x${height}`;
const listeners = {};
let currentUrl = `${pathname}${search}`;
let currentRef = document.referrer;
2020-09-18 22:40:46 +02:00
/* Collect metrics */
2020-07-21 04:24:33 +02:00
const post = (url, data, callback) => {
const req = new XMLHttpRequest();
req.open('POST', url, true);
2022-03-11 04:01:33 +01:00
req.setRequestHeader('Content-Type', 'text/plain');
req.onreadystatechange = () => {
if (req.readyState === 4) {
callback(req.response);
}
};
req.send(JSON.stringify(data));
};
2022-03-05 05:36:13 +01:00
const getPayload = () => ({
website,
hostname,
screen,
language,
cache: useCache && sessionStorage.getItem(cacheKey),
url: currentUrl,
});
const assign = (a, b) => {
Object.keys(b).forEach(key => {
a[key] = b[key];
});
2022-03-05 05:36:13 +01:00
return a;
};
const collect = (type, payload) => {
if (disableTracking()) return;
2020-09-15 13:54:35 +02:00
post(
2020-10-03 05:33:46 +02:00
`${root}/api/collect`,
{
type,
payload,
},
res => useCache && sessionStorage.setItem(cacheKey, res),
2020-10-03 05:33:46 +02:00
);
2020-09-15 13:54:35 +02:00
};
2020-09-16 12:07:22 +02:00
const trackView = (url = currentUrl, referrer = currentRef, uuid = website) => {
2020-09-18 22:40:46 +02:00
collect(
'pageview',
2022-03-05 05:36:13 +01:00
assign(getPayload(), {
website: uuid,
2020-09-18 22:40:46 +02:00
url,
referrer,
2022-03-05 05:36:13 +01:00
}),
2020-09-18 22:40:46 +02:00
);
};
2020-09-18 22:40:46 +02:00
const trackEvent = (event_value, event_type = 'custom', url = currentUrl, uuid = website) => {
2020-09-18 22:40:46 +02:00
collect(
'event',
2022-03-05 05:36:13 +01:00
assign(getPayload(), {
website: uuid,
url,
2020-09-18 22:40:46 +02:00
event_type,
event_value,
2022-03-05 05:36:13 +01:00
}),
2020-09-18 22:40:46 +02:00
);
};
2020-09-18 22:40:46 +02:00
/* Handle events */
2022-03-05 05:36:13 +01:00
const sendEvent = (value, type) => {
const payload = getPayload();
2022-03-11 04:01:33 +01:00
2022-03-05 05:36:13 +01:00
payload.event_type = type;
payload.event_value = value;
2022-03-11 04:01:33 +01:00
const data = JSON.stringify({
type: 'event',
payload,
});
2022-03-05 05:36:13 +01:00
2022-03-11 04:01:33 +01:00
navigator.sendBeacon(`${root}/api/collect`, data);
2022-03-05 05:36:13 +01:00
};
2022-01-15 04:10:46 +01:00
const addEvents = node => {
const elements = node.querySelectorAll(eventSelect);
Array.prototype.forEach.call(elements, addEvent);
};
const addEvent = element => {
2022-01-21 23:49:18 +01:00
(element.getAttribute('class') || '').split(' ').forEach(className => {
if (!eventClass.test(className)) return;
2020-09-18 22:40:46 +02:00
2022-01-21 23:49:18 +01:00
const [, type, value] = className.split('--');
const listener = listeners[className]
? listeners[className]
2022-03-05 05:36:13 +01:00
: (listeners[className] = () => {
if (element.tagName === 'A') {
sendEvent(value, type);
} else {
trackEvent(value, type);
}
});
2022-01-21 23:49:18 +01:00
element.addEventListener(type, listener, true);
});
2020-09-18 22:40:46 +02:00
};
const monitorMutate = mutations => {
mutations.forEach(mutation => {
const element = mutation.target;
addEvent(element);
2022-01-15 04:10:46 +01:00
addEvents(element);
2020-09-18 22:40:46 +02:00
});
};
/* Handle history changes */
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;
const newUrl = url.toString();
if (newUrl.substring(0, 4) === 'http') {
currentUrl = '/' + newUrl.split('/').splice(3).join('/');
} else {
currentUrl = newUrl;
}
if (currentUrl !== currentRef) {
trackView();
2020-09-16 12:07:22 +02:00
}
2020-09-15 13:54:35 +02:00
};
2020-09-18 22:40:46 +02:00
/* Global */
2020-09-16 12:07:22 +02:00
2020-09-18 22:40:46 +02:00
if (!window.umami) {
const umami = eventValue => trackEvent(eventValue);
2020-09-19 00:26:45 +02:00
umami.trackView = trackView;
umami.trackEvent = trackEvent;
2020-07-19 10:57:01 +02:00
2020-09-18 22:40:46 +02:00
window.umami = umami;
}
/* Start */
2020-09-18 22:40:46 +02:00
if (autoTrack && !disableTracking()) {
2020-09-18 22:40:46 +02:00
history.pushState = hook(history, 'pushState', handlePush);
history.replaceState = hook(history, 'replaceState', handlePush);
const update = () => {
2022-01-15 04:10:46 +01:00
if (document.readyState === 'complete') {
addEvents(document);
trackView();
const observer = new MutationObserver(monitorMutate);
observer.observe(document, { childList: true, subtree: true });
}
};
2022-03-05 05:36:13 +01:00
document.addEventListener('readystatechange', update, true);
2022-03-05 05:36:13 +01:00
update();
2020-09-03 17:53:39 +02:00
}
2020-08-21 04:17:27 +02:00
})(window);