Sending Ajax Requests When a Web Page is Closed: A Comprehensive Guide
Introduction
In today’s digital landscape, understanding user behavior and tracking events is crucial for businesses and developers alike. One such event is when a user leaves a web page, which can be a critical moment for reporting and analytics purposes. In this article, we will explore the various ways to send Ajax requests when a web page is closed, ensuring that your reporting and analytics needs are met.
Event Listeners: Monitoring Page Closure
Before diving into sending Ajax requests, it’s essential to understand the two events that can be used to monitor page closure: beforeunload and unload.
- beforeunload: This event is triggered when the document and resources are about to be unloaded, but the document is still visible. It can be canceled, allowing users to refresh the page or close it without triggering the event.
- unload: This event occurs when the page is already being unloaded, and the document’s state is finalized. All resources, including images and iframes, are still present, but the interface is invalid, and errors do not stop the unloading process.
To monitor both events securely, you can use the following approach:
window.addEventListener("beforeunload", function (event) {
// Cancel the event as stated by the standard
event.preventDefault();
// Chrome requires returnValue to be set
event.returnValue = '';
});
window.addEventListener("unload", function () {
// Handle the unload event
});
Sending Ajax Requests
Now that we have our event listeners in place, we can focus on sending Ajax requests when the user leaves the page. There are three schemes to achieve this:
Scheme 1: Synchronous Ajax Request
This method involves sending a synchronous Ajax request, which will block the page’s unloading process. Although effective, it’s not ideal for users, as they will need to wait for the request to complete before closing the page.
var oAjax = new XMLHttpRequest();
oAjax.open('POST', url + '/user/register', false);
oAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
oAjax.onreadystatechange = function () {
if (oAjax.readyState == 4 && oAjax.status == 200) {
var data = JSON.parse(oAjax.responseText);
} else {
console.log(oAjax);
}
};
oAjax.send('a=1&b=2');
Scheme 2: Asynchronous Ajax Request with Abort
In this method, an asynchronous Ajax request is sent, but the browser aborts it when the page is unloaded. However, the server can ignore the abort and still process the request.
var oAjax = new XMLHttpRequest();
oAjax.open('POST', url + '/user/register', true);
oAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
oAjax.onreadystatechange = function () {
if (oAjax.readyState == 4 && oAjax.status == 200) {
var data = JSON.parse(oAjax.responseText);
} else {
console.log(oAjax);
}
};
oAjax.send('a=1&b=2');
Scheme 3: Using navigator.sendBeacon
This method uses the navigator.sendBeacon API to send asynchronous requests when the user leaves the page. It’s ideal for reporting and analytics purposes, as it ensures that the data is sent before the page is unloaded.
navigator.sendBeacon(url, data);
Using navigator.sendBeacon with Different Data Formats
You can use navigator.sendBeacon with various data formats, such as:
- Blob: Send a blob object as the request body.
- FormData: Send a
FormDataobject as the request body. - URLSearchParams: Send a
URLSearchParamsobject as the request body.
Here are some examples:
// Using Blob
var blob = new Blob(['room_id=123'], { type: 'application/x-www-form-urlencoded' });
navigator.sendBeacon('/cgi-bin/leave_room', blob);
// Using FormData
var fd = new FormData();
fd.append('room_id', 123);
navigator.sendBeacon('/cgi-bin/leave_room', fd);
// Using URLSearchParams
var params = new URLSearchParams({ room_id: 123 });
navigator.sendBeacon('/cgi-bin/leave_room', params);
By following these schemes and using navigator.sendBeacon, you can send Ajax requests when a web page is closed, ensuring that your reporting and analytics needs are met.