Repository navigation
Update analytics data sending method - #4002
Shrishti0423 wants to merge 2 commits into
Conversation
Replaced 'unload' event with 'visibilitychange' to send analytics data when the document is hidden.
AKzar1el
left a comment
There was a problem hiding this comment.
The new handler can run repeatedly while the page stays open, but the surrounding section still describes a one-time unload event.
| window.addEventListener("unload", function() { | ||
| navigator.sendBeacon("/analytics", JSON.stringify(analyticsData)); | ||
| document.addEventListener("visibilitychange", function() { | ||
| if (document.visibilityState === "hidden") { |
There was a problem hiding this comment.
visibilitychange also fires when someone switches tabs or minimizes the browser, so this can send the same accumulated analyticsData multiple times without an unload. Could the example either clear the sent batch after a successfully queued beacon or guard one-time reporting, and update the surrounding window.onunload explanation? Otherwise readers copying it may double-count activity.
There was a problem hiding this comment.
Thanks for the feedback! I've updated the example to use a one-time reporting guard based on the return value of navigator.sendBeacon(). This prevents the same analytics data from being queued multiple times when the page becomes hidden repeatedly. I've also updated the surrounding explanation to describe the visibilitychange event and when it fires.
Updated the explanation of using the visibilitychange event and navigator.sendBeacon for sending analytics data.
Updated the analytics example to use the
visibilitychangeevent instead ofunload.The analytics data is sent using
navigator.sendBeacon()when the document becomes hidden, which is more reliable for sending data when a user leaves or switches away from a page.