Last active
March 29, 2024 00:30
-
-
Save ryanmorr/5f06a523c3b9dcdfab6593713810434e to your computer and use it in GitHub Desktop.
The MDN recommended way of executing unload code
This file contains 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
// 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