umami/tracker/index.js

233 lines
5.7 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 _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-_]+)/;
2023-04-04 09:34:07 +02:00
const eventNameAttribute = _data + 'umami-event';
2023-04-21 00:19:09 +02:00
const delayDuration = 300;
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 = () => {
2023-04-04 09:34:07 +02:00
const trackElement = el => {
const attr = el.getAttribute.bind(el);
const eventName = attr(eventNameAttribute);
2023-03-26 13:15:08 +02:00
if (eventName) {
const eventData = {};
2023-04-04 09:34:07 +02:00
el.getAttributeNames().forEach(name => {
2023-03-26 13:15:08 +02:00
const match = name.match(eventRegex);
if (match) {
eventData[match[1]] = attr(name);
}
});
2023-04-04 09:34:07 +02:00
return track(eventName, { data: eventData });
}
return Promise.resolve();
};
2023-03-26 13:15:08 +02:00
2023-04-04 09:34:07 +02:00
const callback = e => {
const findATagParent = (rootElem, maxSearchDepth) => {
let currentElement = rootElem;
for (let i = 0; i < maxSearchDepth; i++) {
2023-04-21 00:19:09 +02:00
if (currentElement.tagName === 'A') {
return currentElement;
2023-04-21 00:19:09 +02:00
}
currentElement = currentElement.parentElement;
}
return null;
};
2023-04-04 09:34:07 +02:00
const el = e.target;
2023-04-21 00:19:09 +02:00
const anchor = el.tagName === 'A' ? el : findATagParent(el, 5);
2023-04-04 09:34:07 +02:00
if (anchor) {
const { href, target } = anchor;
const external =
target === '_blank' ||
e.ctrlKey ||
e.shiftKey ||
e.metaKey ||
(e.button && e.button === 1);
const eventName = anchor.getAttribute(eventNameAttribute);
if (eventName && href) {
if (!external) {
2023-03-26 13:15:08 +02:00
e.preventDefault();
}
2023-04-04 09:34:07 +02:00
return trackElement(anchor).then(() => {
if (!external) location.href = href;
});
2023-03-26 13:15:08 +02:00
}
2023-04-04 09:34:07 +02:00
} else {
trackElement(el);
2023-03-26 13:15:08 +02:00
}
};
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;
const headers = {
2023-04-22 00:55:52 +02:00
'Content-Type': 'application/json',
};
if (typeof cache !== 'undefined') {
headers['x-umami-cache'] = cache;
}
2023-03-26 13:15:08 +02:00
return fetch(endpoint, {
method: 'POST',
body: JSON.stringify({ type: 'event', payload }),
2023-04-22 00:55:52 +02:00
headers,
2023-03-26 13:15:08 +02:00
})
.then(res => res.text())
.then(text => (cache = text));
};
2020-07-19 10:57:01 +02:00
2023-04-22 00:55:52 +02:00
const track = (obj, data) => {
if (typeof obj === 'string') {
return send({
...getPayload(),
name: obj,
data: typeof data === 'object' ? data : undefined,
});
} else if (typeof obj === 'object') {
return send(obj);
} else if (typeof obj === 'function') {
return send(obj(getPayload()));
2023-03-26 13:15:08 +02:00
}
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}`;
2023-04-04 04:34:41 +02:00
let currentRef = document.referrer;
2023-03-26 13:15:08 +02:00
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);