How send data to server when the user leaves the page?

--

Here the problem, you need notify to the server that the users leaves the page, why?

for many reasons for example:

  • Unlock content. if only allow 1 user by Content.
  • Stop a asynchronous process.
  • Analytics and diagnostics.
  • Or simply know that the user leaves the page/app.

The first solution for solve this issue could be use the unload event:

The unload event is fired when the document or a child resource is being unloaded.

But here we have a problem, if a request is trigger at this point, the browser simply cancel the request and close the tab/window.

Beacon API

Fortunately the web specification prevent this issue and provide a simple solution:

navigator.sendBeacon

what is a beacon?

Beacon: A signaling or guiding device that emits light, such as a lighthouse.

ok the sendBeacon method provide a solution for this issue because allows send data to the server before the document is unloaded.

Why is special?

because send the data asynchronous “when the User Agent has an opportunity to do so” — MDN web docs.

Solution:

Use sendBeacon with unload event:

window.addEventListener('unload', () => {
navigator.sendBeacon(url, data)
})

Works very well BUT here some important points:

  • The method is only POST.
  • Data must be one of:

A ArrayBuffer, ArrayBufferView, Blob, DOMString, FormData, or URLSearchParams object containing the data to send.

  • And you can’t add custom headers.

I used a simple string, and works ok:

window.addEventListener('unload', () => {
navigator.sendBeacon(url, 'uuid: xxxxx-xxx-xx-xxx')
})

IMPORTANT:

Here says that the Beacon API not is perfect and has a failure rate between 1% and 3%, (I want believe that now at the final of 2020, the issue is solved by the browsers 🙏)

Conclusion:

The Beacon API is a great solution for a specific issue, is easy to use but is limited -and could not be perfect-.

--

--