umami/src/tracker/index.js

275 lines
6.6 KiB
JavaScript
Raw Normal View History

2020-08-21 02:17:27 +00:00
(window => {
const {
screen: { width, height },
navigator: { language },
location,
2020-11-02 06:01:30 +00:00
localStorage,
document,
history,
} = window;
const { hostname, href } = location;
const { currentScript, referrer } = document;
if (!currentScript) return;
const _data = 'data-';
const _false = 'false';
const _true = 'true';
const attr = currentScript.getAttribute.bind(currentScript);
const website = attr(_data + 'website-id');
const hostUrl = attr(_data + 'host-url');
const tag = attr(_data + 'tag');
const autoTrack = attr(_data + 'auto-track') !== _false;
const excludeSearch = attr(_data + 'exclude-search') === _true;
const domain = attr(_data + 'domains') || '';
const domains = domain.split(',').map(n => n.trim());
const host =
hostUrl || '__COLLECT_API_HOST__' || currentScript.src.split('/').slice(0, -1).join('/');
const endpoint = `${host.replace(/\/$/, '')}__COLLECT_API_ENDPOINT__`;
const screen = `${width}x${height}`;
2023-03-26 11:15:08 +00:00
const eventRegex = /data-umami-event-([\w-_]+)/;
2023-04-04 07:34:07 +00:00
const eventNameAttribute = _data + 'umami-event';
2023-04-20 22:19:09 +00:00
const delayDuration = 300;
2022-08-28 22:55:18 +00:00
2023-03-26 11:15:08 +00:00
/* Helper functions */
const encode = str => {
2024-03-28 03:05:19 +00:00
if (!str) {
return undefined;
}
try {
const result = decodeURI(str);
if (result !== str) {
return result;
}
} catch (e) {
return str;
}
return encodeURI(str);
};
const parseURL = url => {
try {
const { pathname, search } = new URL(url);
url = pathname + search;
} catch (e) {
/* empty */
}
return excludeSearch ? url.split('?')[0] : url;
};
2020-07-21 02:24:33 +00:00
2022-03-05 04:36:13 +00:00
const getPayload = () => ({
website,
hostname,
screen,
language,
title: encode(title),
url: encode(currentUrl),
referrer: encode(currentRef),
2024-04-02 04:33:04 +00:00
tag: tag ? tag : undefined,
2022-03-05 04:36:13 +00:00
});
/* Event handlers */
2020-09-16 10:07:22 +00:00
const handlePush = (state, title, url) => {
2021-02-02 06:49:00 +00:00
if (!url) return;
currentRef = currentUrl;
currentUrl = parseURL(url.toString());
2021-02-02 06:49:00 +00:00
if (currentUrl !== currentRef) {
2023-03-26 11:15:08 +00:00
setTimeout(track, delayDuration);
2020-09-16 10:07:22 +00:00
}
2020-09-15 11:54:35 +00:00
};
const handlePathChanges = () => {
const hook = (_this, method, callback) => {
const orig = _this[method];
2023-03-26 11:15:08 +00:00
return (...args) => {
callback.apply(null, args);
2023-03-26 11:15:08 +00:00
return orig.apply(_this, args);
};
};
history.pushState = hook(history, 'pushState', handlePush);
history.replaceState = hook(history, 'replaceState', handlePush);
};
const handleTitleChanges = () => {
const observer = new MutationObserver(([entry]) => {
2023-04-22 00:59:03 +00:00
title = entry && entry.target ? entry.target.text : undefined;
});
2023-03-26 11:15:08 +00:00
2023-04-25 01:07:27 +00:00
const node = document.querySelector('head > title');
if (node) {
observer.observe(node, {
subtree: true,
characterData: true,
childList: true,
});
}
};
const handleClicks = () => {
document.addEventListener(
'click',
async e => {
const isSpecialTag = tagName => ['BUTTON', 'A'].includes(tagName);
const trackElement = async el => {
const attr = el.getAttribute.bind(el);
const eventName = attr(eventNameAttribute);
if (eventName) {
const eventData = {};
el.getAttributeNames().forEach(name => {
const match = name.match(eventRegex);
if (match) {
eventData[match[1]] = attr(name);
}
});
return track(eventName, eventData);
}
};
const findParentTag = (rootElem, maxSearchDepth) => {
let currentElement = rootElem;
for (let i = 0; i < maxSearchDepth; i++) {
if (isSpecialTag(currentElement.tagName)) {
return currentElement;
}
currentElement = currentElement.parentElement;
if (!currentElement) {
return null;
}
}
};
const el = e.target;
const parentElement = isSpecialTag(el.tagName) ? el : findParentTag(el, 10);
if (parentElement) {
const { href, target } = parentElement;
const eventName = parentElement.getAttribute(eventNameAttribute);
if (eventName) {
if (parentElement.tagName === 'A') {
const external =
target === '_blank' ||
e.ctrlKey ||
e.shiftKey ||
e.metaKey ||
(e.button && e.button === 1);
if (eventName && href) {
if (!external) {
e.preventDefault();
}
return trackElement(parentElement).then(() => {
if (!external) location.href = href;
});
}
} else if (parentElement.tagName === 'BUTTON') {
return trackElement(parentElement);
}
}
} else {
return trackElement(el);
}
},
true,
);
};
/* Tracking functions */
const trackingDisabled = () =>
!website ||
(localStorage && localStorage.getItem('umami.disabled')) ||
(domain && !domains.includes(hostname));
2024-01-15 03:04:02 +00:00
const send = async (payload, type = 'event') => {
2023-03-26 11:15:08 +00:00
if (trackingDisabled()) return;
const headers = {
2023-04-21 22:55:52 +00:00
'Content-Type': 'application/json',
};
if (typeof cache !== 'undefined') {
headers['x-umami-cache'] = cache;
}
2024-01-15 03:04:02 +00:00
try {
const res = await fetch(endpoint, {
method: 'POST',
body: JSON.stringify({ type, payload }),
headers,
});
const text = await res.text();
2024-01-15 03:04:02 +00:00
return (cache = text);
} catch (e) {
2024-01-15 03:04:02 +00:00
/* empty */
}
2023-03-26 11:15:08 +00:00
};
2020-07-19 08:57:01 +00:00
2024-08-27 21:01:29 +00:00
const init = () => {
if (!initialized) {
track();
handlePathChanges();
handleTitleChanges();
handleClicks();
initialized = true;
}
};
2023-04-21 22:55:52 +00: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 11:15:08 +00:00
}
2023-04-22 04:28:02 +00:00
return send(getPayload());
2023-03-26 11:15:08 +00:00
};
const identify = data => send({ ...getPayload(), data }, 'identify');
/* Start */
2020-09-18 20:40:46 +00:00
2023-03-26 11:15:08 +00:00
if (!window.umami) {
window.umami = {
track,
identify,
2023-03-26 11:15:08 +00:00
};
}
let currentUrl = parseURL(href);
let currentRef = referrer !== hostname ? referrer : '';
2023-03-26 11:15:08 +00:00
let title = document.title;
let cache;
let initialized;
if (autoTrack && !trackingDisabled()) {
2024-08-27 21:01:29 +00:00
if (document.readyState === 'complete') {
init();
} else {
document.addEventListener('readystatechange', init, true);
}
2020-09-03 15:53:39 +00:00
}
2020-08-21 02:17:27 +00:00
})(window);