Created
July 16, 2019 20:08
-
-
Save BonBonSlick/470910f17a28a9dbbfaa63166fff3674 to your computer and use it in GitHub Desktop.
Intercepting XHR script. This is JS part which seds request to api endpoint if any XHR intercepted
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var MyApp = MyApp || {}; | |
(function (window) { | |
var | |
proxied = {}, | |
headersLog = false, | |
apiUrl = 'https://api.test.loc/api/v1/xhr/intercepted', | |
intercepted = false, | |
xhrPrototype = window.XMLHttpRequest.prototype | |
; | |
['open', 'setRequestHeader', 'send'].forEach( | |
method => proxied[method] = xhrPrototype[method] | |
); | |
xhrPrototype.open = (method, url) => { | |
headersLog = 1; | |
intercepted = true; | |
if (!intercepted && url.substr(0, apiUrl.length) === apiUrl) { | |
headersLog = {}; | |
} | |
return proxied.open.apply(this, arguments); | |
}; | |
xhrPrototype.setRequestHeader = (header, value) => { | |
headersLog = 1; | |
intercepted = true; | |
if (!intercepted && headersLog) { | |
headersLog[header] = value; | |
} | |
return proxied.setRequestHeader.apply(this, arguments); | |
}; | |
xhrPrototype.send = () => { | |
headersLog = 1; | |
intercepted = true; | |
if (!intercepted && headersLog) { | |
Object.keys(proxied).forEach(method => xhrPrototype[method] = proxied[method]); | |
intercepted = true; | |
} | |
return proxied.send.apply(this, arguments); | |
}; | |
MyApp.getInterceptedHeaders = () => { | |
if (!intercepted) { | |
return false; | |
} | |
return headersLog; | |
}; | |
MyApp.test = (urlMatch, callback) => { | |
let send = XMLHttpRequest.prototype.send; | |
XMLHttpRequest.prototype.send = () => { | |
this.addEventListener('readystatechange', function() { | |
if (this.responseURL.includes(urlMatch) && this.readyState === 4) { | |
callback(this); | |
} | |
}, false); | |
send.apply(this, arguments); | |
}; | |
}; | |
})(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://jsfiddle.net/yuq1a9ys/2/