reporting-lib
Version:
A comprehensive monitoring and reporting library for web applications
59 lines • 2.21 kB
JavaScript
import { lazyReportCache } from '../report/index.js';
import { isValidOssVideoUrl, getRequestBodySize } from '../util/tool.js';
const originalPrototype = XMLHttpRequest.prototype;
const originalOpen = originalPrototype.open;
const originalSend = originalPrototype.send;
function overWriteOpenAndSend() {
originalPrototype.open = function newOpen(...args) {
this.url = args[1];
this.method = args[0];
originalOpen.apply(this, args);
};
originalPrototype.send = function newSend(...args) {
this.startTime = Date.now();
const body = args[0];
this.requestSize = getRequestBodySize(body);
const onLoadEnd = () => {
this.endTime = Date.now();
this.duration = this.endTime - this.startTime;
const { status, duration, startTime, endTime, method, response, requestSize } = this;
let { url } = this;
let code = status;
let request_url = url;
try {
code = JSON.parse(response).code;
}
catch {
}
if (isValidOssVideoUrl(request_url)) {
request_url = `https://sd-cms-bmp.oss-accelerate.aliyuncs.com:443/mbp/video`;
}
let reportData = {
status,
duration,
// startTime,
// endTime,
request_url,
method: method || 'GET',
code,
// success: status >= 200 && status < 300,
// sub_type: 'xhr',
// request_size: parseInt(requestSize/1000),
};
try {
reportData.request_size = parseInt(requestSize / 1000);
}
catch (error) {
}
lazyReportCache('api', reportData);
this.removeEventListener('loadend', onLoadEnd, true);
};
//当请求结束时触发,无论请求成功 (load) 还是失败 (abort 或 error)
this.addEventListener('loadend', onLoadEnd, true);
originalSend.apply(this, args);
};
}
export default function xhr() {
overWriteOpenAndSend();
}
//# sourceMappingURL=xhr.js.map