Adrià Vilanova Martínez | 43ec2b9 | 2021-07-16 18:44:54 +0200 | [diff] [blame] | 1 | import * as utils from '../common/xhrInterceptorUtils.js'; |
| 2 | |
| 3 | const originalOpen = XMLHttpRequest.prototype.open; |
| 4 | const originalSend = XMLHttpRequest.prototype.send; |
| 5 | |
avm99963 | 1f50f6f | 2021-08-12 23:04:41 +0200 | [diff] [blame] | 6 | let messageID = 0; |
| 7 | |
Adrià Vilanova Martínez | 43ec2b9 | 2021-07-16 18:44:54 +0200 | [diff] [blame] | 8 | XMLHttpRequest.prototype.open = function() { |
| 9 | this.$TWPTRequestURL = arguments[1] || location.href; |
avm99963 | 1f50f6f | 2021-08-12 23:04:41 +0200 | [diff] [blame] | 10 | this.$TWPTID = messageID++; |
Adrià Vilanova Martínez | 43ec2b9 | 2021-07-16 18:44:54 +0200 | [diff] [blame] | 11 | |
| 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 => { |
avm99963 | 1f50f6f | 2021-08-12 23:04:41 +0200 | [diff] [blame] | 18 | utils.triggerEvent(i.eventName, body, this.$TWPTID); |
Adrià Vilanova Martínez | 43ec2b9 | 2021-07-16 18:44:54 +0200 | [diff] [blame] | 19 | }); |
| 20 | }); |
| 21 | } |
| 22 | |
| 23 | originalOpen.apply(this, arguments); |
| 24 | }; |
| 25 | |
| 26 | XMLHttpRequest.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 => { |
avm99963 | 1f50f6f | 2021-08-12 23:04:41 +0200 | [diff] [blame] | 46 | utils.triggerEvent(i.eventName, JSONBody, this.$TWPTID); |
Adrià Vilanova Martínez | 43ec2b9 | 2021-07-16 18:44:54 +0200 | [diff] [blame] | 47 | }); |
| 48 | } |
| 49 | }; |