blob: 3ea4474617c81864b4d58d355d368443de1c3727 [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
avm999631f50f6f2021-08-12 23:04:41 +02006let messageID = 0;
7
Adrià Vilanova Martínez43ec2b92021-07-16 18:44:54 +02008XMLHttpRequest.prototype.open = function() {
9 this.$TWPTRequestURL = arguments[1] || location.href;
avm999631f50f6f2021-08-12 23:04:41 +020010 this.$TWPTID = messageID++;
Adrià Vilanova Martínez43ec2b92021-07-16 18:44:54 +020011
12 let interceptors = utils.matchInterceptors('response', this.$TWPTRequestURL);
13 if (interceptors.length > 0) {
14 this.addEventListener('load', function() {
15 var body = utils.getResponseJSON(this);
16 if (body !== undefined)
17 interceptors.forEach(i => {
avm999631f50f6f2021-08-12 23:04:41 +020018 utils.triggerEvent(i.eventName, body, this.$TWPTID);
Adrià Vilanova Martínez43ec2b92021-07-16 18:44:54 +020019 });
20 });
21 }
22
23 originalOpen.apply(this, arguments);
24};
25
26XMLHttpRequest.prototype.send = function() {
27 originalSend.apply(this, arguments);
28
29 let interceptors =
30 utils.matchInterceptors('request', this.$TWPTRequestURL || location.href);
31 if (interceptors.length > 0) {
32 var rawBody = arguments[0];
33 if (typeof (rawBody) !== 'object' ||
34 !(rawBody instanceof Object.getPrototypeOf(Uint8Array))) {
35 console.error(
36 'Request body is not Uint8Array, but ' + typeof (rawBody) + '.',
37 this.$TWPTRequestUrl);
38 return;
39 }
40
41 var dec = new TextDecoder('utf-8');
42 var body = dec.decode(rawBody);
43 var JSONBody = JSON.parse(body);
44
45 interceptors.forEach(i => {
avm999631f50f6f2021-08-12 23:04:41 +020046 utils.triggerEvent(i.eventName, JSONBody, this.$TWPTID);
Adrià Vilanova Martínez43ec2b92021-07-16 18:44:54 +020047 });
48 }
49};