Home > Web Front-end > JS Tutorial > Introduction to the Beacon API

Introduction to the Beacon API

Lisa Kudrow
Release: 2025-02-20 09:57:10
Original
736 people have browsed it

Introduction to the Beacon API

Key Takeaways

  • The Beacon API provides a solution for web developers to send small amounts of data, such as analytics or diagnostics, back to the server asynchronously while the current page is unloading, solving the issue of potential delay or loss of valuable information.
  • The Beacon API consists of one method, sendBeacon, that is attached to the navigator object. It takes two parameters, the URL to submit data to and the data to be submitted. The data is submitted via a HTTP POST request and can be sent as an ArrayBufferView, a Blob, a DOMString, or a FormData object.
  • The Beacon API is supported by the major desktop browsers like Chrome, Firefox, and Opera, but not in the latest versions of IE and Safari. For browsers without support, developers can use feature detection and fallback to older methods of submitting data on page unload.

The Beacon API makes it easy for web developers to send small amounts of data, such as analytics or diagnostics data, back to the server asynchronously while the current page is unloading. In this article, we’ll look at some of the problems the Beacon API solves, and show you how to use the API.

Without the Beacon API, sending data back to your server when the user navigates away from a page can be trickier than it seems. You don’t want to delay the next page from loading, as this would harm the user’s experience of your site. Yet you don’t want to loose valuable information that could help improve your site: sending the data too early might mean you loose valuable information that you could have captured if you’d waited a fraction longer.

A typical solution to that sends analytics data to the server as the document unloads might look something like this:

<span>window.addEventListener('unload', function(event) {
</span>  <span>var xhr = new XMLHttpRequest(),
</span>    data <span>= captureAnalyticsData(event);
</span>
  xhr<span>.open('post', '/log', false);
</span>  xhr<span>.send(data);
</span><span>});
</span>
<span>function captureAnalyticsData(event) {
</span>  <span>return 'sample data';
</span><span>}</span>
Copy after login
Copy after login

An unload event handler, that submits data via an Ajax request. When the page unload event fires, the data is captured via the captureAnalyticsData function, and sent to the server via an Ajax request. Note the third parameter to xhr.open is false, indicating the Ajax request is synchronous. Browsers typically ignore asynchronous requests made during an unload handler, so any such Ajax request has to be synchronous. As it’s synchronous, the browser has to wait for the request to complete before it can unload the document and display the next page. This extra waiting around can lead to the perception of poor performance.

Other techniques used instead of a synchronous Ajax request include setting the src of an Image object in the unload handler. The browser will wait for the Image to load before unloading the document, during which time data can be submitted to the server. However, this still has the same problem: the unloading of the current document will be delayed while the request, this time for the Image, completes, which can lead to the perception of poor performance.

The Beacon API was created to help solve these issues. It defines an interface that lets developers send small amounts of data to the web server asynchronously. It consists of just one method, sendBeacon, that is attached to the navigator object. sendBeacon takes two parameters, the URL you want to submit data to and the data to be submitted:

<span>window.addEventListener('unload', function(event) {
</span>  <span>var xhr = new XMLHttpRequest(),
</span>    data <span>= captureAnalyticsData(event);
</span>
  xhr<span>.open('post', '/log', false);
</span>  xhr<span>.send(data);
</span><span>});
</span>
<span>function captureAnalyticsData(event) {
</span>  <span>return 'sample data';
</span><span>}</span>
Copy after login
Copy after login

Data is submitted via a HTTP POST request, and can be sent as an ArrayBufferView, a Blob, a DOMString, or a FormData object. The browser queues the request, and sends it “at the earliest available opportunity, but MAY prioritize the transmission of data lower compared to other network traffic.” (as per the W3C spec). sendBeacon returns true if the data was successfully submitted to the server, or false otherwise.

Support for navigator.sendBeacon is decent across the major desktop browsers. You’ll find it supported in the current versions of Chrome, Firefox, and Opera, but not in the latest versions of IE and Safari. As you can’t guarantee it’s availability though, you’re best bet is to use feature detection and fallback to one of the old methods of submitting data on page unload:

<span>window.addEventListener('unload', function(event) {
</span>  <span>var data = captureAnalyticsData(event);
</span>  <span>navigator.sendBeacon('/log', data);
</span><span>});</span>
Copy after login

I’ve created a little sample app that you can use to see the Beacon API in action. You’ll need to have Node.js installed to run the server. To run the sample:

  1. Download and unzip the zip file into a folder of your choice e.g. beaconapi
  2. Open your terminal and change directory into the folder you created in Step 1 e.g. cd /path/to/beaconapi
  3. Still in the terminal, type in npm install and press
  4. Now type in DEBUG=beaconapi_demo ./bin/www and press
  5. Open a browser that supports the Beacon API and point it to http://localhost:3000

You should see a page that looks like this:

Introduction to the Beacon API

In this example, we’re using Chrome. Open the Dev Tools, switch to the Network tab, and tick the Preserve Log checkbox. Filter the results so you just see the Other requests. Now, when you click the Unload button, you should see the requests to /log logged in the dev tools.

Introduction to the Beacon API

Conclusion

This article has introduced the Beacon API. It is a very small API, but fills a specific niche. Hopefully you are able to put it to good use.

Frequently Asked Questions (FAQs) about Beacon API

What is the primary function of the Beacon API?

The Beacon API is a web API that allows web applications to send data from the user’s browser to the server in an efficient and non-blocking manner. This API is particularly useful for sending analytics data, which can be sent without affecting the user’s browsing experience. The Beacon API ensures that the data is sent even if the user navigates away from the page or closes the browser.

How does the Beacon API differ from AJAX?

While both AJAX and the Beacon API are used to send data from the client to the server, they differ in their use cases and behavior. AJAX is typically used for fetching data from the server and updating the web page without reloading it. On the other hand, the Beacon API is used for sending data to the server, especially analytics data, without blocking the user’s browsing experience. Unlike AJAX, the Beacon API ensures that the data is sent even if the user navigates away from the page or closes the browser.

How can I use the Beacon API in my web application?

To use the Beacon API in your web application, you can use the navigator.sendBeacon() method. This method takes two arguments: the URL to send the data to, and the data to send. The data can be a FormData object, a Blob, an ArrayBufferView, or a URLSearchParams object. Here’s an example:

var data = new FormData();
data.append('name', 'John Doe');
navigator.sendBeacon('/api/endpoint', data);

What are the benefits of using the Beacon API?

The Beacon API offers several benefits for web applications. First, it allows you to send data to the server in a non-blocking manner, which means it doesn’t affect the user’s browsing experience. Second, it ensures that the data is sent even if the user navigates away from the page or closes the browser. This makes it ideal for sending analytics data, which can be sent at the end of the user’s session without risking data loss.

Are there any limitations or drawbacks to using the Beacon API?

One limitation of the Beacon API is that it doesn’t provide any feedback on whether the data was successfully received by the server. This means you can’t use it for critical data that requires confirmation of receipt. Additionally, the Beacon API is not supported in all browsers, so you may need to provide a fallback for browsers that don’t support it.

How does the Beacon API handle failures?

The Beacon API does not provide any feedback on whether the data was successfully received by the server. If the data cannot be sent, for example, due to network issues, the API will not retry sending the data. This is why it’s recommended to use the Beacon API for non-critical data that doesn’t require confirmation of receipt.

Can I use the Beacon API to send data to a different domain?

Yes, you can use the Beacon API to send data to a different domain. However, the server must support CORS (Cross-Origin Resource Sharing) and must be configured to accept cross-origin requests from your domain.

Is the Beacon API supported in all browsers?

The Beacon API is supported in most modern browsers, including Chrome, Firefox, Safari, and Edge. However, it’s not supported in Internet Explorer. You can check the current browser support on websites like Can I Use.

Can I send large amounts of data with the Beacon API?

The Beacon API is designed for sending small amounts of data, such as analytics data. While there’s no hard limit on the amount of data you can send, sending large amounts of data may impact the user’s network performance. Therefore, it’s recommended to use the Beacon API for sending small amounts of non-critical data.

Can I cancel a beacon request?

No, once a beacon request is made, it cannot be cancelled. The Beacon API does not provide a way to cancel or undo a beacon request. This is another reason why it’s recommended to use the Beacon API for non-critical data that doesn’t require confirmation of receipt.

The above is the detailed content of Introduction to the Beacon API. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template