Skip to content

Instantly share code, notes, and snippets.

@BonBonSlick
Created July 16, 2019 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BonBonSlick/470910f17a28a9dbbfaa63166fff3674 to your computer and use it in GitHub Desktop.
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
'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);
@BonBonSlick
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment