Skip to content

Instantly share code, notes, and snippets.

@djeikyb
Created August 13, 2020 18:48
Show Gist options
  • Save djeikyb/3b00b796a4260c215aa82ddf53b0d931 to your computer and use it in GitHub Desktop.
Save djeikyb/3b00b796a4260c215aa82ddf53b0d931 to your computer and use it in GitHub Desktop.
intercept requests to example.com, enable automatic cookie sending
type myfetch = (input: RequestInfo, init?: RequestInit) => Promise<Response>;
function isRequest(rq: any): rq is Request {
return (rq as Request).url !== undefined;
}
(function (fetch: myfetch) {
window.fetch = async function (this: myfetch, input: RequestInfo, init) {
let url;
if (isRequest(input)) {
url = new URL(input.url);
} else if (input.startsWith("http")) {
url = new URL(input);
}
// debugger;
const newinit: RequestInit = { ...init };
if (url && url.hostname.match(/\.example\.com$/)) {
newinit.credentials = "include";
}
return await fetch.apply(this, [input, newinit]);
};
})(window.fetch);
type xhropen = (
method: string,
url: string,
async?: boolean,
username?: string | null,
password?: string | null
) => void;
(function (open: xhropen) {
XMLHttpRequest.prototype.open = function (
this: XMLHttpRequest,
method: string,
url: string,
async?: boolean,
username?: string | null,
password?: string | null
) {
const res = open.apply(this, [method, url, async, username, password]);
const u = new URL(url);
if (u.hostname.match(/example\.com$/i)) {
this.withCredentials = true;
// this.setRequestHeader("X-fnord", "see them");
}
return res;
};
})(XMLHttpRequest.prototype.open);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment