AJAX - Using the Beacon API for Asynchronous Data Transmission in AJAX Applications

 
 

1. Introduction

The Beacon API is a modern web technology that allows websites to send small amounts of data to a web server asynchronously without delaying the user's navigation or affecting the normal operation of a webpage. It is particularly useful when a website needs to transmit information in the background, especially when a user closes a webpage, moves to another page, or leaves a website.

In traditional AJAX applications, developers commonly use XMLHttpRequest or the Fetch API to exchange information between a browser and a server without reloading the entire webpage. However, these methods may not always complete successfully when a user navigates away from the current page. For example, when a website tries to send analytics information just before a user closes the browser tab, the request may be interrupted because the browser is busy navigating to another page. The Beacon API addresses this problem by providing a reliable mechanism for sending background data without interfering with page navigation.

2. What Is the Beacon API?

The Beacon API is a browser technology designed to transmit small amounts of data from a webpage to a server asynchronously. It uses the navigator.sendBeacon() method to send information without requiring the browser to wait for a response.

Unlike traditional AJAX requests, the Beacon API does not provide a mechanism for receiving the server's response. Its primary purpose is to deliver data to a server while allowing the browser to continue its normal activities.

For example, consider an online shopping website that wants to record how long a customer spends viewing a particular product. When the customer moves to another page, the website can use the Beacon API to send the viewing information to the server. This allows the website to collect useful analytical information without interrupting the customer's browsing experience.

The Beacon API is especially suitable for:

  • Website usage analytics.

  • User activity tracking.

  • Performance monitoring.

  • Recording page navigation information.

  • Sending diagnostic information.

  • Collecting small background application updates.

3. How the Beacon API Works

The Beacon API works by sending data from the browser to a specified server endpoint in the background. The browser handles the transmission independently, allowing the webpage to continue navigating or being closed.

The process generally involves the following steps:

Step 1: Collecting Information

The website collects the information that needs to be transmitted. This may include page-view details, user interaction statistics, performance measurements, or other application data.

Step 2: Preparing the Data

The collected information is converted into a suitable format, such as a JSON string or a FormData object, before transmission.

Step 3: Calling the sendBeacon() Method

The website uses the navigator.sendBeacon() method to submit the collected information to the server.

Step 4: Background Transmission

The browser places the information into a queue for transmission. The request can continue even when the webpage is being unloaded or the user navigates to another page.

Step 5: Server Processing

The server receives the transmitted information and processes it according to the application's requirements. For example, an analytics server may store the information in a database for future analysis.

4. Syntax of the Beacon API

The basic syntax of the Beacon API is:

navigator.sendBeacon(url, data);

Here:

  • navigator represents the browser's navigation-related interface.

  • sendBeacon() is the method used to transmit data asynchronously.

  • url specifies the server endpoint where the information should be sent.

  • data represents the information being transmitted. It can be a string, Blob, FormData, URLSearchParams, or another supported data type.

The method returns a Boolean value.

  • true indicates that the browser successfully queued the data for transmission.

  • false indicates that the browser could not queue the data.

It is important to understand that a return value of true does not guarantee that the server successfully received or processed the information.

5. Example of Implementing the Beacon API

The following example demonstrates how the Beacon API can send page activity information to a server when a user leaves a webpage.

window.addEventListener("pagehide", function () {

    const activityData = {
        page: window.location.href,
        event: "Page Closed",
        timestamp: new Date().toISOString()
    };

    const data = JSON.stringify(activityData);

    const status = navigator.sendBeacon(
        "/analytics",
        data
    );

    if (status) {
        console.log("Analytics data queued successfully");
    } else {
        console.log("Unable to queue analytics data");
    }

});

Explanation:

In this example, the pagehide event detects when the webpage is being hidden as part of navigation or when the user leaves the page.

The application collects three pieces of information: the current webpage URL, the event description, and the current timestamp.

The JSON.stringify() method converts the collected information into a JSON string. The navigator.sendBeacon() method then sends this information to the /analytics server endpoint.

If the browser successfully queues the information, the method returns true. Otherwise, it returns false.

This approach allows the website to transmit important activity information without requiring the user to wait for the request to finish.

6. Difference Between the Beacon API and Traditional AJAX

Although the Beacon API and traditional AJAX technologies support asynchronous communication, they are designed for different purposes.

Feature

Traditional AJAX

Beacon API

Main purpose

Exchange data between browser and server

Send small amounts of background data

Server response

Can receive and process responses

Does not expose the server response

Navigation handling

Requests may be interrupted during navigation

Designed to support transmission during page unloading

Response processing

Supports response handling

Does not support response handling

Best application

Dynamic webpage updates and data retrieval

Analytics and background reporting

Data transmission

Supports different request methods and configurations

Uses a POST request

The Beacon API is not a complete replacement for AJAX. Instead, it provides an additional communication mechanism for situations where sending data in the background is more important than receiving an immediate response.

7. Advantages of Using the Beacon API

The Beacon API offers several advantages for modern web applications.

Non-Blocking Data Transmission: It allows websites to transmit information without making users wait for the request to finish. This helps maintain a smooth browsing experience.

Useful During Page Navigation: It is designed to send information even when a user navigates away from a webpage. This makes it valuable for collecting analytics and performance information.

Reduced Request Interruption: Unlike ordinary asynchronous requests that may be interrupted during page unloading, Beacon requests are designed to continue independently of the webpage's navigation lifecycle.

Simple Implementation: Developers can use a single method, navigator.sendBeacon(), to send data to a server without writing complex asynchronous request-handling code.

Improved User Experience: Since the browser handles the transmission in the background, the user can continue browsing without unnecessary delays.

8. Limitations of the Beacon API

Despite its advantages, the Beacon API has certain limitations that developers should consider.

No Server Response: The API does not provide access to the server's response. Therefore, it is unsuitable for applications that need to display returned information or confirm server-side processing.

Limited Data Size: The Beacon API is intended for transmitting relatively small amounts of data. Browsers may reject requests when the total amount of queued data becomes too large.

Limited Request Configuration: Developers cannot directly configure request methods, custom headers, or other advanced request options through sendBeacon().

No Guaranteed Delivery: Successfully queuing a request does not guarantee that the server will receive or process it. Applications requiring guaranteed delivery should use an appropriate acknowledgement or retry mechanism.

POST Requests Only: The Beacon API sends data using HTTP POST requests. It cannot be used when another HTTP method is required.

9. Practical Applications of the Beacon API

The Beacon API is useful in several real-world web development situations.

Website Analytics: Websites can collect information about page visits, browsing duration, and user navigation patterns. This information helps website owners understand how visitors interact with their platforms.

E-Commerce Applications: Online shopping websites can record product-viewing activity, shopping-cart interactions, and navigation events to understand customer behaviour.

Performance Monitoring: Developers can transmit information about page loading time, resource performance, and other diagnostic measurements to monitoring servers.

Educational Websites: Online learning platforms can record course navigation, lesson completion events, and learning activity statistics without interrupting students.

Content Management Systems: Websites built using content management systems can use the Beacon API to collect background activity information and monitor user interactions.

10. Conclusion

The Beacon API is an important web technology that improves background data transmission in modern AJAX-based applications. It allows websites to send small amounts of information to servers without interrupting page navigation or requiring users to wait for a response. Its ability to transmit analytics, performance measurements, and user activity information during page unloading makes it particularly useful for monitoring and reporting applications.

Although it does not replace traditional AJAX techniques such as XMLHttpRequest and Fetch API, it complements them by addressing a specific communication requirement. By understanding how the Beacon API works, its advantages, limitations, and practical applications, developers can build more efficient web applications that collect important information while maintaining a smooth user experience.