The latest sendBeacon documentation on MDN, states "The navigator.sendBeacon() method asynchronously sends a small amount of data over HTTP to a web server. It’s intended to be used in combination with the visibilitychange event (but not with the unload and beforeunload events)."
To use the visibilitychange
event like suggested, you could
document.addEventListener('visibilitychange', function() {
if (document.visibilityState === 'hidden') {
navigator.sendBeacon(handleClose);
}
});
I have experienced similar issues with trying send data on the unload
event. Is the user base all on desktop? Mobile devices don't reliably fire the unload
event. The Page Lifecycle API provides the visibility change event and the pagehide
events which could be used together to get closer to your desired result.
The Page Lifecycle API attempts to solve this problem by:
Introducing and standardizing the concept of lifecycle states on the web.
Defining new, system-initiated states that allow browsers to limit the resources that can be consumed by hidden or inactive tabs.
Creating new APIs and events that allow web developers to respond to transitions to and from these new system-initiated states.
source
The issue you are experiencing is likely more of an issue without how browsers suspend pages or discard them entirely. Unfortunately, browsers are not unified on how they do this, and to add to the complexity there is different behavior on desktop vs. mobile.
There are several threads that dive in deeper to this issue if you are interested. Until browsers standardize on this, I'm not sure there is an easy answer, such as "use x event".
Issue filed on Page Visibility
Issue on MDN's strints about sendBeacon
unload and beforeunload aren’t the right events to use with sendBeacon. Instead, use visibilitychange.
it does not work on close withvisibilitychange
event either! – Softhearted