Created
January 15, 2025 00:41
-
-
Save oscarduignan/b52cc29c3431b7d05753bdab857dff1c to your computer and use it in GitHub Desktop.
Logging events to server from javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| }) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <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> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 -oand check devtools then you'll that when you leave the page or close window the events are sent to serverhappens 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