3

I am using navigator.sendBeacon to send a small payload in the onclick event of an anchor

<a href="https://someurl.com" onclick="navigator.sendBeacon('https://internalurl.com/')">Click Here</a>

But it seems that the user does not navigate away until the server response is received from the sendBeacon call. i.e., if I put a breakpoint in my server-side endpoint, the browser does not navigate to 'https://someurl.com' until I hit continue on my server-side debugger. The docs (https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon) say the call should be async.

Is this the expected behaviour or am I missing something?

sheamus
  • 3,001
  • 4
  • 31
  • 54
  • 2
    That's weird. `sendBeacon` shouldn't behave like you described. AFAIK, it was originally implemented to just drop the packet without respecting server's respond at all, which is good practice for analytic or just `ping`-ing. I also tried to [reproduce](https://codesandbox.io/s/admiring-brown-tg73m) without success. Can you elaborate more? This might be interesting – choz May 31 '21 at 16:34
  • Are someurl.com and `internalurl.com` on the same server? Could it be that this server is only able to process one request at a time, so the `someurl.com` request waits in queue until `internalurl.com` is processed? – Draex_ Jan 26 '22 at 12:02
  • sendBeacon() is not intended to be used used in onclick() event; it's intended for **unload events** to capture critical data at the last moment when user leaves the page. Try replacing **fetch API** for this. That should do what you intend without blocking the navigation with proper sync settings in the call. Check this example for proper use case of sendBeacon() usage in this [**timeonsite JS**](https://saleemkce.github.io/timeonsite/docs/index.html#real-time-example) tracker example – webblover Jun 22 '22 at 07:13

0 Answers0