I have the following useEffect hook in a React component:
useEffect(() => {
const handleUnload = function (event) {
navigator.sendBeacon("https://webhook.site/8c3a42ce-c525-4a84-8783-f65175ed1297", JSON.stringify({ "foo": "bar" }));
}
window.addEventListener('beforeunload', handleUnload);
return () => {
window.removeEventListener('beforeunload', handleUnload);
}
}, []);
Where the URL is just some test server that I've confirmed is working using Postman. However when I close the browser, the request is not received.
I have 2 questions:
Why does this not work?
Is there any way to send an array of javascript objects with sendBeacon?
Many thanks