UNPKG

react-activity-tracker

Version:

A library to track user interactions and API activity in React apps

40 lines (33 loc) 986 B
export default function patchXHR(onTrack) { const originalOpen = XMLHttpRequest.prototype.open; const originalSend = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.open = function (method, url) { this._method = method; this._url = url; return originalOpen.apply(this, arguments); }; XMLHttpRequest.prototype.send = function (body) { const xhr = this; const requestBody = body ? tryParseJSON(body) : null; xhr.addEventListener('loadend', function () { const responseBody = tryParseJSON(xhr.responseText); onTrack({ type: 'api', label: '', url: xhr._url, method: xhr._method, requestBody, responseBody, status: xhr.status, }); }); return originalSend.apply(this, arguments); }; } function tryParseJSON(data) { try { return typeof data === 'string' ? JSON.parse(data) : data; } catch { return data; } }