Skip to content

Instantly share code, notes, and snippets.

@oscarduignan
Created January 15, 2025 00:41
Show Gist options
  • Select an option

  • Save oscarduignan/b52cc29c3431b7d05753bdab857dff1c to your computer and use it in GitHub Desktop.

Select an option

Save oscarduignan/b52cc29c3431b7d05753bdab857dff1c to your computer and use it in GitHub Desktop.
Logging events to server from javascript
const { timeOrigin } = window.performance
const unsentEvents = []
console.log("Analytics loaded") // shows that it is only run once, even though imported into multiple scripts
document.addEventListener("visibilitychange", function sendAnalytics() {
if (document.visibilityState === "hidden") {
const events = unsentEvents.splice(0)
const payload = {
timeOrigin,
events
}
if (window.analyticsEndpoint) {
if (!navigator.sendBeacon( // max size of payload is 64kb
window.analyticsEndpoint,
new Blob([JSON.stringify(payload)], { type: "application/json" })
)) {
unsentEvents.unshift(...events) // could grow bigger and bigger if request fails and page isn't closed
}
} else {
console.error("window.analyticsEndpoint not set, logging to console", payload)
}
}
})
export function log(event, data) {
unsentEvents.push({
event,
data,
time: window.performance.now() // monotonic from timeOrigin
})
}
<html>
<head>
</head>
<body>
<script type="module">
import { log } from "./analytics.js"
log("event.1", { userId: 1 });
setTimeout(() => log("event.2", { userId: 1 }), 1000);
setTimeout(() => log("event.3", { userId: 1 }), 2000);
</script>
<script type="module">
import { log } from "./analytics.js"
setTimeout(() => {
log("event.4", { userId: 1 })
console.log("All events logged")
}, 3000);
</script>
</body>
</html>
@oscarduignan
Copy link
Author

someone asked us how to log stuff to kibana and I went down a rabbit hole of exploring MDN articles

if you create the two files above and run npx http-server -o and check devtools then you'll that when you leave the page or close window the events are sent to server

happens on visibility hidden so that it triggers more reliably than using "unload" on mobile devices

https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment