Skip to content

Instantly share code, notes, and snippets.

@ajhsu
Forked from jasperck/XHRMITM.js
Last active April 4, 2023 14:43
Show Gist options
  • Save ajhsu/6ef9de3879445a4e934b3735ae242385 to your computer and use it in GitHub Desktop.
Save ajhsu/6ef9de3879445a4e934b3735ae242385 to your computer and use it in GitHub Desktop.
To intercept and modify the response, browser could render with your mutation
const responseTransform = requestURL => response => {
// Original request url
console.log(requestURL);
// Deep clone from response
const nextResponse = JSON.parse(JSON.stringify(response));
// do what you want with response
if (nextResponse.results_json) {
nextResponse.results_json.search_results.map(r => {
r.listing.name = '顆顆';
});
}
return nextResponse;
};
// XMLHttpRequest MITM attack implementation
(function() {
const XHR = window.XMLHttpRequest;
function nextXHR() {
const xhr = new XHR();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
const response = responseTransform(xhr.responseURL)(
xhr.responseText !== '' ?
JSON.parse(xhr.responseText) : {}
);
// Unlock and overwrite the responseText
Object.defineProperty(xhr, 'responseText', {
writable: true
});
xhr.responseText = JSON.stringify(response);
}
};
return xhr;
}
window.XMLHttpRequest = nextXHR;
})();
@ajhsu
Copy link
Author

ajhsu commented Nov 12, 2016

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