umami/scripts/umami/index.js

57 lines
1.3 KiB
JavaScript
Raw Normal View History

2020-07-18 02:15:29 +00:00
import 'promise-polyfill/src/polyfill';
import 'unfetch/polyfill';
const HOST_URL = process.env.UMAMI_URL;
const SESSION_VAR = 'umami.session';
const {
screen: { width, height },
navigator: { language },
location: { hostname, pathname, search },
localStorage: store,
document,
} = window;
2020-07-17 08:03:38 +00:00
function post(url, params) {
return fetch(url, {
method: 'post',
2020-07-18 10:33:33 +00:00
cache: 'no-cache',
headers: {
'Content-Type': 'application/json',
},
2020-07-18 10:44:54 +00:00
body: params,
2020-07-17 08:03:38 +00:00
}).then(res => res.json());
}
2020-07-18 02:15:29 +00:00
const script = document.querySelector('script[data-website-id]');
if (script) {
2020-07-17 08:03:38 +00:00
const website_id = script.getAttribute('data-website-id');
if (website_id) {
2020-07-18 02:15:29 +00:00
const referrer = document.referrer;
2020-07-17 08:03:38 +00:00
const screen = `${width}x${height}`;
const url = `${pathname}${search}`;
2020-07-18 02:15:29 +00:00
if (!store.getItem(SESSION_VAR)) {
post(`${HOST_URL}/api/session`, {
2020-07-17 08:03:38 +00:00
website_id,
hostname,
url,
screen,
language,
2020-07-18 02:15:29 +00:00
}).then(session => {
store.setItem(SESSION_VAR, JSON.stringify(session));
2020-07-17 08:03:38 +00:00
});
}
2020-07-18 02:15:29 +00:00
post(`${HOST_URL}/api/collect`, {
2020-07-17 08:03:38 +00:00
type: 'pageview',
2020-07-18 02:15:29 +00:00
payload: { url, referrer, session: JSON.parse(store.getItem(SESSION_VAR)) },
}).then(response => {
if (!response.status) {
store.removeItem(SESSION_VAR);
}
2020-07-17 08:03:38 +00:00
});
}
2020-07-18 02:15:29 +00:00
}