Skip to content

Instantly share code, notes, and snippets.

@ryanmorr
Last active March 29, 2024 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanmorr/5f06a523c3b9dcdfab6593713810434e to your computer and use it in GitHub Desktop.
Save ryanmorr/5f06a523c3b9dcdfab6593713810434e to your computer and use it in GitHub Desktop.
The MDN recommended way of executing unload code
// https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon#sending_analytics_at_the_end_of_a_session
const callbacks = [];
function unload(callback) {
callbacks.push(callback);
};
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
callbacks.forEach((callback) => callback());
}
});
// Usage:
unload(() => {
navigator.sendBeacon('/log', analyticsData);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment