I am trying to send data when the window closes to prevent 2 people from editing and overwriting each others data. Currently I am using a sendBeacon within a unload event handler.
FireFox:
- Refresh: Works
- Back button: Works
- Close window: Works
Chrome:
- Refresh: Works
- Back button: Works
- Close window: Doesn't work
Here is my code
function sendDataOnClose(edit,trans){
var url = "../../save.php"; //This has a post request handler and works properly with other functions for saving data
const data = JSON.stringify
({
"translations": trans,
"edit": edit
});
navigator.sendBeacon(url, data);
}
function handleClose(){
if(edit){
console.log("sending a false when edit is: "+ edit)
sendDataOnClose(false, translations);
}
}
window.addEventListener('unload', handleClose);
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
visibilitychangeevent like suggested, you couldI have experienced similar issues with trying send data on the
unloadevent. Is the user base all on desktop? Mobile devices don't reliably fire theunloadevent. The Page Lifecycle API provides the visibility change event and thepagehideevents which could be used together to get closer to your desired result.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