Record the API used at the burial point
Buried some background
Collect the movement of the user’s cursor on the page in a period of time, including cursor movement and clicking:
- Collects statistics about the stay duration of a user on a site
- Collect the number of clicks on page links, etc
- The request is not sent when the user closes or jumps out of the page.
Statistical method:
- When the current page is closed
- Statistical timing: Unload, beforeUnload events
- Problem: The request was not sent when the user closed or jumped out of the page
- The statistics are displayed on the new page
- Statistical timing: Data is passed to the next hop page and data is sent to the next hop page
- Problem: The same statistics script must be deployed in the drop-down page
Analysis of several schemes
By beForunload orunload events
The statistical scheme is closed
The solution of the current page closing statistical scheme is to block the page closing, send the data statistics request first, and then close the page
- Block AJAX requests and use synchronous AJAX
window.addEventListener('unload'.e= > {
sendLog()
},
false
)
function sendLog() {
var xhr = new XMLHttpRequest()
// Synchronize the request
xhr.open(
'post',
url,
false
)
xhr.setRequestHeader('Content-Type'.'application/json; charset=UTF-8'.false)
const data = dealLogData({
eventName: 'nov_lottery_page_demodmeo'.properties: {
eventId: 'Active page'.label: 'Display November Lucky draw page'
}
})
xhr.send(JSON.stringify(data))
}
Copy the code
- Block AJAX requests with img
window.addEventListener('unload'.e= > {
this.postPoint({
eventName: 'nov_lottery_page_demodmeo'.properties: {
eventId: 'Active page'.label: 'Active page'}})new Image().src =
'https://tse1-mm.cn.bing.net/th/id/OET.da357be831fd4520a7b69594bcba30b4?w=272&h=272&c=7&rs=1&o=5&pid=1.9'
},
false
)
Copy the code
- Beacon API
The Beacon interface is used to send asynchronous and non-blocking requests to the server. Beacon requests use the POST method of the HTTP protocol and usually do not require a response. This request is guaranteed to be sent before the Unload state of the page goes from start to finish. You don’t need a blocking request, such as XMLHttpRequest.
window.addEventListener('unload'.function(event) {
navigator.sendBeacon('/collector', data);
});
Copy the code
Everything is fine in the development environment, on the real machine, everything… Not normal! You’ll notice that this method works fine on IOS devices, but on Android devices it doesrequest header
forCORS-safelisted-request-header