blob: 8630ca33f38eafea2d8fa7ecaf2a2d3b71dac6af [file] [log] [blame]
Adrià Vilanova Martínez43ec2b92021-07-16 18:44:54 +02001import * as utils from '../common/xhrInterceptorUtils.js';
2
3const originalOpen = XMLHttpRequest.prototype.open;
4const originalSend = XMLHttpRequest.prototype.send;
5
6XMLHttpRequest.prototype.open = function() {
7 this.$TWPTRequestURL = arguments[1] || location.href;
8
9 let interceptors = utils.matchInterceptors('response', this.$TWPTRequestURL);
10 if (interceptors.length > 0) {
11 this.addEventListener('load', function() {
12 var body = utils.getResponseJSON(this);
13 if (body !== undefined)
14 interceptors.forEach(i => {
15 utils.triggerEvent(i.eventName, body);
16 });
17 });
18 }
19
20 originalOpen.apply(this, arguments);
21};
22
23XMLHttpRequest.prototype.send = function() {
24 originalSend.apply(this, arguments);
25
26 let interceptors =
27 utils.matchInterceptors('request', this.$TWPTRequestURL || location.href);
28 if (interceptors.length > 0) {
29 var rawBody = arguments[0];
30 if (typeof (rawBody) !== 'object' ||
31 !(rawBody instanceof Object.getPrototypeOf(Uint8Array))) {
32 console.error(
33 'Request body is not Uint8Array, but ' + typeof (rawBody) + '.',
34 this.$TWPTRequestUrl);
35 return;
36 }
37
38 var dec = new TextDecoder('utf-8');
39 var body = dec.decode(rawBody);
40 var JSONBody = JSON.parse(body);
41
42 interceptors.forEach(i => {
43 utils.triggerEvent(i.eventName, JSONBody);
44 });
45 }
46};