Introduction to Web Beacon API
What is Beacon API?
The Beacon API is a JavaScript web API for sending data from the browser to the web server without expecting to get a response. It is used to send analytics, diagnostics, and logging data which doesn't need a response.
Why Beacon API?
You have probably use ajax to send all kinds of data to a server using XMLHttpRequest. One of the challanges ajax can't do is that: it can't make requests when the page is unloaded; because browsers will ignore those requests. This is where Beacon API come into play. Because it doesn't wait for a response; you can make requests using beacon API while the page is unloading.
Beacon API is a great alternative to ajax for sending data like analytics, diagnostics, and logging data; where you don't expect to get a response. It is done asynchronously and the browser will make requests in idle time. Which will greatly improve the user experience.
Beacon API solves Ajax problems
Ajax problems:
Difficult to in some cases like page unload
Might impact on application/web page performance
Beacon API solves the above problems
Send data and don't require a response
Data is sending during the idle time
How to send data with the Beacon API?
Now we have a better understanding of what beacon is, what it is capable of, and why we might use it. Let's get started with the API.
navigator.sendBeacon(targetUrl, data);
The first argument is the URL that the data send to and the second argument is the data to be sent. The data can be string, array buffer, blob object, and form data.
The function returns true if the browser is able to schedule the data to be sent and false otherwise. Let's try see an example.
/**
* Send event to the web server
* @param {Object} data
*/
function sendEvent(data) {
// Check to see if the beacon API is available in this browser
if (navigator.sendBeacon) {
// Send the data to analytics url
navigator.sendBeacon('/analytics', data);
} else {
// TODO: XMLHttpRequest Ajax
}
}
/**
* Listen to button click event
*/
document.getElementById('btn').addEventListener('click', function(e) {
sendEvent('Button is pressed.');
});
/**
* Listen to page unload event
*/
window.addEventListener('unload', function(e) {
sendEvent('Page unload');
});
Conclusion
The beacon API is very useful when you need to send data to the server without require a response. Due to the fact that it will schedule the data to send in idle time; as a result, it won't impact the app performance.