# Beacon API

The Beacon API is used to send a small amount of data to a web server asynchronously from the user agent. It is primarily intended for sending analytics, diagnostics, and logging data.

## 1. The Problem: Sending Data on Unload

Web developers often want to send data to the server when the user leaves the page (e.g., session duration, tracking clicks). Historically, developers used `unload` or `beforeunload` events with `XMLHttpRequest` or `fetch`.

However, browsers often ignore asynchronous requests made during these events to ensure the next page loads quickly. Synchronous requests (blocking the UI) were used as a workaround, but they degrade the user experience by freezing the browser.

## 2. The Solution: `navigator.sendBeacon()`

The `navigator.sendBeacon()` method solves this by queuing the data to be sent asynchronously. The browser guarantees to initiate the beacon request before the page is unloaded and allows the request to run to completion without blocking the execution of other code or the loading of the next page.

## 3. Syntax

```javascript
navigator.sendBeacon(url, data);
```

*   **`url`**: The URL that will receive the data.
*   **`data`**: The data to send. It can be an `ArrayBuffer`, `ArrayBufferView`, `Blob`, `DOMString`, `FormData`, or `URLSearchParams`.

**Returns:** `true` if the user agent successfully queued the data for transfer, otherwise `false`.

## 4. Example: Sending Analytics

```javascript
document.addEventListener('visibilitychange', function() {
  if (document.visibilityState === 'hidden') {
    const analyticsData = JSON.stringify({
      event: 'page_hidden',
      timestamp: Date.now(),
      url: window.location.href
    });

    // Use Blob to set the correct Content-Type
    const blob = new Blob([analyticsData], { type: 'application/json' });
    
    navigator.sendBeacon('/api/log', blob);
  }
});
```

## 5. Key Characteristics

*   **Asynchronous:** Does not block the main thread.
*   **Reliable:** Designed specifically to work during page unload.
*   **POST Method:** Beacons are always sent as HTTP POST requests.
*   **No Response:** You cannot access the server's response. It is a "fire and forget" mechanism.

[[programming/javascript/vanilla/javascript]]
[[programming/javascript/vanilla/ajax-fetch]]
[[programming/javascript/vanilla/page-visibility-api]]