Search code examples
javascriptajaxbrowserxmlhttprequest

Are XHR requests created in an anchor tags click handler guaranteed to be sent?


I'm sure this information exists out there but my googling abilities are failing me here.

What I want to know, is if I trigger a XHR request in an anchor tags click event handler, is that request guaranteed to be sent? I don't care about handling the response, but I don't know if it's possible for the request to never leave the unsent state before navigating away.

For example, say I want to track all anchor tag clicks so I do something like this:

$("a").on("click", () => $.ajax({ url: "/track_link_click", method: "POST" });

Is there a situation where the request in the event handler never gets sent? I could prevent the location change from taking place until response is received but I'd much rather not.

Thanks in advance!


Solution

  • There's no guarantee, by design, but in practice I'm pretty sure all browsers will at least get the request sent away.

    I suggest you look into navigator.sendBeacon() which is designed for exactly this type of thing. Its purpose is to guarantee that the request gets sent even if it has to happen after the page unloads. https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon

    It's not supported in IE and not yet in Safari, so you'll need to rely on the regular AJAX method as a fallback.