Skip to content

Instantly share code, notes, and snippets.

@navio
Last active August 10, 2020 15:23
Show Gist options
  • Save navio/ce2329ab5171a7f03708c2ef233104de to your computer and use it in GitHub Desktop.
Save navio/ce2329ab5171a7f03708c2ef233104de to your computer and use it in GitHub Desktop.
Browser Proxy - Overwriting Fetch / XMLHTTPRequest
function ProxyEngine(initialRules = []) {
const storedRules = JSON.parse((localStorage.getItem(keyStorage) || '[]'));
const rules = new Map([...initialRules, ...storedRules]);
const matchRules = (url,response) => {
const element = [...rules.keys()].find((rule) => url.indexOf(rule) > 1);
if (element){
const rule = rules.get(element);
console.log('🦑 Matched:',element);
return ( typeof rule === 'function' ) ? rule(response, console.log ) : rule ;
}
return element;
};
const matchRulesAsync = async (url,response) => {
const element = [...rules.keys()].find((rule) => url.indexOf(rule) > 1);
if (element){
const rule = rules.get(element);
console.log('🦑 Matched:',element);
return ( typeof rule === 'function' ) ? await rule(response, console.log ) : await rule ;
}
return element;
};
// localStorage.setItem(keyStorage,JSON.stringify(Array.from(rules.entries())))
const originalXHR = window.XMLHttpRequest;
const internalXHR = function () {
const xhr = new originalXHR;
for (const attr in xhr) {
if ( attr === 'onreadystatechange' ) {
xhr.onreadystatechange = (...args) => {
if(this.readyState === 4){
const overwrite = matchRules(xhr.responseURL, xhr);
if (overwrite) {
this.response = overwrite;
this.responseText = overwrite;
}
}
this.onreadystatechange && this.onreadystatechange.apply(this, args);
}
continue;
} else if (attr === 'onload') {
xhr.onload = (...args) => {
const overwrite = matchRules(this.responseURL, xhr);
if(overwrite){
this.response = overwrite;
this.responseText = overwrite;
}
this.onload && this.onload.apply(this, args);
}
continue;
}
if (typeof xhr[attr] === 'function') {
this[attr] = xhr[attr].bind(xhr);
} else {
if (attr === 'responseText' || attr === 'response') {
Object.defineProperty(this, attr, {
get: () => this[`_${attr}`] == undefined ? xhr[attr] : this[`_${attr}`],
set: (val) => this[`_${attr}`] = val,
enumerable: true
});
} else {
Object.defineProperty(this, attr, {
get: () => xhr[attr],
set: (val) => xhr[attr] = val,
enumerable: true
});
}
}
}
}
const originalFetch = window.fetch;
const internalFetch = async (...args) => originalFetch(...args).then(async (response) => {
const responseOverwritter = (response, toOverwrite) => {
const stream = textToStream(JSON.stringify(toOverwrite));
return new Response(stream, {
headers: response.headers,
status: response.status,
statusText: response.statusText,
});
};
const textToStream = (txt = "") =>
new ReadableStream({
start(controller) {
const bufView = new Uint8Array(new ArrayBuffer(txt.length));
for (var i = 0; i < txt.length; i++) {
bufView[i] = txt.charCodeAt(i);
}
controller.enqueue(bufView);
controller.close();
},
});
const shouldRewrite = async (original) => {
const overwrite = await matchRulesAsync(original.url,response);
if (overwrite) {
return responseOverwritter(original, overwrite);
} else {
return original;
}
};
return shouldRewrite(response);
});
const enable = () => {
window.fetch = internalFetch;
window.XMLHttpRequest = internalXHR;
}
const disable = () => {
window.fetch = originalFetch
window.XMLHttpRequest = originalXHR;
}
const addRule = (match, rule) => rules.set(match,rule);
const removeRule = (match) => rules.delete(match);
return {
enable,
disable,
addRule,
removeRule
}
}
const proxy = ProxyEngine();
@navio
Copy link
Author

navio commented Aug 10, 2020

The idea is to be able to overwrite response in the browser. Helpful for extensions and apps.

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