When you want to send some tracking-related information to the server from a webpage, there is another option that is often recommended over directly using fetch
to send requests: navigator.sendBeacon
.
Why is this recommended?
Because if you use the usual method of sending requests, there may be issues when the user closes the page or navigates away. For example, if a request is sent just as the page is being closed, that request may not go through and could be canceled along with the page closure.
Although there are ways to try to force the request to be sent, these methods often harm the user experience, such as forcing the page to close later or sending a synchronous request.
navigator.sendBeacon
was created to solve this problem.