Capture pushState events.

This commit is contained in:
Mike Cao 2020-07-18 22:51:17 -07:00
parent 58a1c63407
commit eebf145efc
6 changed files with 81 additions and 48 deletions

1
.gitignore vendored
View File

@ -14,7 +14,6 @@
# production # production
/build /build
/public/umami.js
# misc # misc
.DS_Store .DS_Store

View File

@ -17,7 +17,7 @@ export default function Layout({ title, children }) {
<script <script
async async
defer defer
data-website-id="865234ad-6a92-11e7-8846-b05adad3f099" data-website-id="d0059975-b79a-4f83-8926-ed731475fded"
src="/umami.js" src="/umami.js"
/> />
)} )}

View File

@ -5,7 +5,7 @@ import { allowPost } from 'lib/middleware';
export default async (req, res) => { export default async (req, res) => {
await allowPost(req, res); await allowPost(req, res);
let result = { success: 0, time: Date.now() }; let result = { success: 0 };
const { const {
website_id, website_id,
@ -23,6 +23,7 @@ export default async (req, res) => {
if (website) { if (website) {
const session = await getSession(session_id); const session = await getSession(session_id);
const time = Date.now();
if (!session) { if (!session) {
await createSession(website_id, session_id, { await createSession(website_id, session_id, {
@ -40,7 +41,8 @@ export default async (req, res) => {
success: 1, success: 1,
session_id, session_id,
website_id, website_id,
hash: hash(`${website_id}${session_id}${result.time}`), time,
hash: hash(`${website_id}${session_id}${time}`),
}; };
} }
} }

View File

@ -1,14 +1,19 @@
import React from 'react'; import React from 'react';
import Layout from 'components/layout'; import Layout from 'components/layout';
import Link from 'next/link';
export default function Home() { export default function Home() {
return ( return (
<Layout> <Layout>
Hello. Hello.
<br /> <br />
<a href="/?q=abc">abc</a> <Link href="/?q=abc">
<a>abc</a>
</Link>
<br /> <br />
<a href="/?q=123">123</a> <Link href="/?q=123">
<a>123</a>
</Link>
</Layout> </Layout>
); );
} }

1
public/umami.js Normal file

File diff suppressed because one or more lines are too long

View File

@ -1,63 +1,89 @@
import 'promise-polyfill/src/polyfill'; import 'promise-polyfill/src/polyfill';
import 'unfetch/polyfill'; import 'unfetch/polyfill';
const HOST_URL = process.env.UMAMI_URL;
const SESSION_VAR = 'umami.session';
const { const {
screen: { width, height }, screen: { width, height },
navigator: { language }, navigator: { language },
location: { hostname, pathname, search }, location: { hostname, pathname, search },
localStorage: store, localStorage: store,
document, document,
history,
} = window; } = window;
const post = (url, params) =>
fetch(url, {
method: 'post',
cache: 'no-cache',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(params),
}).then(res => res.json());
const createSession = data =>
post(`${HOST_URL}/api/session`, data).then(({ success, ...session }) => {
if (success) {
store.setItem(SESSION_VAR, JSON.stringify(session));
return success;
}
});
const getSession = () => JSON.parse(store.getItem(SESSION_VAR));
const pageView = (url, referrer) =>
post(`${HOST_URL}/api/collect`, {
type: 'pageview',
payload: { url, referrer, session: getSession() },
}).then(({ success }) => {
if (!success) {
store.removeItem(SESSION_VAR);
}
return success;
});
const script = document.querySelector('script[data-website-id]'); const script = document.querySelector('script[data-website-id]');
if (script) { if (script) {
const website_id = script.getAttribute('data-website-id'); const website_id = script.getAttribute('data-website-id');
if (website_id) { if (website_id) {
const referrer = document.referrer; const sessionKey = 'umami.session';
const hostUrl = new URL(script.src).origin;
const screen = `${width}x${height}`; const screen = `${width}x${height}`;
const url = `${pathname}${search}`; let currentUrl = `${pathname}${search}`;
const data = { website_id, hostname, url, screen, language }; let currenrRef = document.referrer;
if (!store.getItem(SESSION_VAR)) { const post = (url, params) =>
createSession(data).then(success => success && pageView(url, referrer)); fetch(url, {
} else { method: 'post',
pageView(url, referrer).then(success => !success && createSession(data)); cache: 'no-cache',
} headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(params),
}).then(res => res.json());
const createSession = data =>
post(`${hostUrl}/api/session`, data).then(({ success, ...session }) => {
if (success) {
store.setItem(sessionKey, JSON.stringify(session));
return success;
}
});
const getSession = () => JSON.parse(store.getItem(sessionKey));
const getSessionData = url => ({ website_id, hostname, url, screen, language });
const pageView = (url, referrer) =>
post(`${hostUrl}/api/collect`, {
type: 'pageview',
payload: { url, referrer, session: getSession() },
}).then(({ success }) => {
if (!success) {
store.removeItem(sessionKey);
}
return success;
});
const execute = (url, referrer) => {
const data = getSessionData(url);
if (!store.getItem(sessionKey)) {
createSession(data).then(success => success && pageView(url, referrer));
} else {
pageView(url, referrer).then(success => !success && createSession(data));
}
};
const handlePush = (state, title, url) => {
currenrRef = currentUrl;
currentUrl = url;
execute(currentUrl, currenrRef);
};
const hook = (type, cb) => {
const orig = history[type];
return (state, title, url) => {
const args = [state, title, url];
cb.apply(null, args);
return orig.apply(history, args);
};
};
history.pushState = hook('pushState', handlePush);
history.replaceState = hook('replaceState', handlePush);
execute(currentUrl, currenrRef);
} }
} }