sendBeacon not working in beforeunload handler

361 Views Asked by At

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:

  1. Why does this not work?

  2. Is there any way to send an array of javascript objects with sendBeacon?

Many thanks

0

There are 0 best solutions below