Table of Contents
Key Takeaways
Conclusion
Frequently Asked Questions (FAQs) about Beacon API
What is the primary function of the Beacon API?
How does the Beacon API differ from AJAX?
How can I use the Beacon API in my web application?
What are the benefits of using the Beacon API?
Are there any limitations or drawbacks to using the Beacon API?
How does the Beacon API handle failures?
Can I use the Beacon API to send data to a different domain?
Is the Beacon API supported in all browsers?
Can I send large amounts of data with the Beacon API?
Can I cancel a beacon request?
Home Web Front-end JS Tutorial Introduction to the Beacon API

Introduction to the Beacon API

Feb 20, 2025 am 09:57 AM

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles