DEV Community

Le Vuong
Le Vuong

Posted on

How to send request when user close a web page?

As developers, we often need to send a final request to the server when a user leaves a page — for example:

  • Sending final analytics data
  • Tracking session duration
  • Logging abandonment events
  • Saving last-known state

On older browsers, we can do this with a fetch request in the beforeunload event.

However, this approach is unreliable because browsers aggressively terminate asynchronous work when a page is closing.

On modern browsers, the navigator.sendBeacon() method can be used for this purpose.

window.addEventListener('visibilitychange', function() {
  if (document.visibilityState === 'hidden') {
    navigator.sendBeacon('/log', JSON.stringify({ event: 'page_closed' }));
  }
});
Enter fullscreen mode Exit fullscreen mode

This method is built specifically for analytics-style requests.

Top comments (0)