Some ways to upload front-end embedded data

Data burying point

The terminology in the field of data collection refers to related technologies and implementation processes for capturing, processing, and sending user behaviors or specific events. It is the data monitoring and data uploading of specific events or user behaviors.

type of data

We monitor a project from three dimensions, that is, a certain subject that the system is oriented to, monitoring of individual parts of the system for the differences in use of different subjects, and overall overall monitoring of the system's operation process; that is, users behavior, page performance, product anomalies. Therefore we can divide it into three categories:

1. Data monitoring (involving user behavior and corresponding events)

2. Performance monitoring (involving page performance and rendering interaction)

3. Abnormal monitoring (involving runtime anomalies of the product system)

At the same time, we can give a rough range of data structures:

pv: Number of page views
uv: Number of user visits
Custom events about users
About page performance loading data
Exception information about errors

Front-end burying method

Now that we understand the related concepts of how to bury points on the front end, let’s talk about the methods of burying points, that is, what methods can be used to monitor the data of buried points.

1. XMLHttpRequest

This usage method is actually to agree on an interface, and then submit a request to report data, such as:

function buryingPoint(data) {
    
    
  return new Promise((resolve, reject) => {
    
    
    // 创建XMLHttpRequest
    const xhr = new XMLHttpRequest();
    // 定义请求接口
    xhr.open("post", '/buryingPoint', true);
    // 发送数据
    xhr.send(data);
  });
}

let info = {
    
    }
buryingPoint(info) // 这样就成功上报了info的对象

When we call the buryingPoint method, the data is reported to the server.

However, this traditional way of burying requests generally involves cross-domain risks, and it must be synchronous, otherwise the request will be easily interrupted.

2. script and link

By using the traditional request method to bury data, we can see that the implementation of data reporting does not emphasize the interaction between the front and back ends. Therefore, we can also implement the data reporting function through some tags that support cross-domain. like:

let a = document.createElement('script')
a.src = 'https://www.test.com/web/buryingPoint/test.js?test=123'
document.body.appendChild(a)

Create a script tag, put the data we need to transfer after the src address, and mount this tag on the page, thus realizing data reporting in the script+link method.
Another advantage of using script tags is that they are compatible and can adapt to different browsers.
However, this method also has disadvantages, that is, it needs to be mounted on the page, and repeated operations on the DOM will affect page performance, and loading js/css resources will also block page rendering, affecting the user experience. Frequent reporting is not suitable This way.

3. img

Different from the script tag, the advantage of using the img tag is that there is no need to mount it on the page and repeatedly operate the dom; and the loading of img will not block the parsing of html. The img does not render after loading. It needs to wait for the Render Tree to be generated. Rendered together with Render Tree.

Note: Generally, gif images are used for hidden point reporting. A legal gif image only requires 43 bytes.

like:

function buryingPoint(src) {
    
    
    var img = document.createElement("img");
    img.src = src;
}

buryingPoint('https://www.test.com/web/buryingPoint/test.gif?test=123')

In addition to the img tag, we can also use new image(). After setting its src, we can directly request the image.

四、 Navigator.sendBeacon

Navigator.sendBeacon is currently a common tracking reporting solution. The Navigator.sendBeacon method accepts two parameters. The first parameter is the URL of the target server, and the second parameter is the data to be sent (optional), which can be of any type ( Strings, form objects, binary objects, etc.).

In the past, to solve this problem, statistics and diagnostic code were often placed in

1. Initiate a synchronous XMLHttpRequest to send data.
2. Create an element and set src. Most user agents will delay unloading the document to load the image.
3. Create a no-op loop of a few seconds.

All of the above methods force the user agent to delay unloading the document and cause the next navigation to appear later. The next page can't do anything about this poor loading performance.

This is the purpose of the sendBeacon() method. Using the sendBeacon() method will cause the user agent to asynchronously send data to the server when it has the opportunity, without delaying the unloading of the page or affecting the loading performance of the next navigation. This means:

1. Data transmission is reliable.
2. Data is transmitted asynchronously.
3. Does not affect the loading of the next navigation. Data is sent
via HTTP POST request.

like:

function buryingPoint(url, data) {
    
    
    navigator.sendBeacon(url, data)
}

buryingPoint('https://www.test.com/web/buryingPoint',{
    
    time: Date.now()})

At present, the most suitable data upload solution is navigator.sendBeacon, which is not only asynchronous, but also not restricted by the same domain, and is a task of the browser, so it can guarantee that the data will be sent out without affecting page unloading.

Common front-end pitfalls

List some common front-end buried points:

Click to trigger buried point

Bind the click event triggered by user behavior. When the target element is clicked, the buried data reporting is triggered.

function clickButton(url, data) {
    
    
    navigator.sendBeacon(url, data)
}
Report the time spent on the page.

In the routing file, initialize a startTime, and when the page leaves, calculate the residence time through the routing guard.

let url = ''// 上报地址
let startTime = Date.now()
let currentTime = ''
router.beforeEach((to, from, next) => {
    
     
     if (to) {
    
    
         currentTime = Date.now()
         stayTime = parseInt(currentTime - startTime)
         navigator.sendBeacon(url, {
    
    time: stayTime})
         startTime = Date.now()
     }
})
Error monitoring points

Receive error information through the listening function.

//  vue错误捕获
app.config.errorHandler = (err) => {
    
     
    navigator.sendBeacon(url, {
    
    error: error.message, text: 'vue运行异常' })
}

//  JS异常与静态资源加载异常
window.addEventListener('error', (error) => {
    
     
    if (error.message) {
    
     
        navigator.sendBeacon(url, {
    
    error: error.message, text: 'js执行异常' })
    } else {
    
     
        navigator.sendBeacon(url, {
    
    error: error.filename, text: '资源加载异常' })
    } 
}, true)

//  请求错误捕获
axios.interceptors.response.use(
  (response) => {
    
    
    if (response.code == 200) {
    
    
      return Promise.resolve(response);
    } else {
    
    
      return Promise.reject(response);
    }
  },
  (error) => {
    
    
    // 返回错误逻辑
    navigator.sendBeacon(url, {
    
    error: error, text: '请求错误异常' })
  }
);

Content is visible

Use the cross observer to monitor whether the current element appears on the page.

// 可见性发生变化后的回调 
function callback(data) {
    
     
    navigator.sendBeacon(url, {
    
     target: data[0].target, text: '内容可见' }) 
} 
// 交叉观察器配置项 
let options = {
    
    }; 
// 生成交叉观察器 
const observer = new IntersectionObserver(callback); 
// 获取目标节点 
let target = document.getElementById("target"); 
// 监听目标元素 
observer.observe(target);

Regardless of the content, seo keywords: [Data upload] [Front-end buried point] [Data buried point] [Exception capture upload] [Click behavior upload] [Click upload] [Request upload] [Visual upload]

Guess you like

Origin blog.csdn.net/xiaorunye/article/details/130528337