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>
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>
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>
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:
- Download and unzip the zip file into a folder of your choice e.g. beaconapi
- Open your terminal and change directory into the folder you created in Step 1 e.g. cd /path/to/beaconapi
- Still in the terminal, type in npm install and press
- Now type in DEBUG=beaconapi_demo ./bin/www and press
- Open a browser that supports the Beacon API and point it to http://localhost:3000
You should see a page that looks like this:
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.
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.
