Skip to content

Instantly share code, notes, and snippets.

@tksugimoto
Created June 10, 2017 03:21
Show Gist options
  • Save tksugimoto/2b2a32ffe27b3142f5d764ee1085c3df to your computer and use it in GitHub Desktop.
Save tksugimoto/2b2a32ffe27b3142f5d764ee1085c3df to your computer and use it in GitHub Desktop.
JavaScript fetch APIを書き換えて通信内容を変更する
(() => {
const isTarget = response => response.url.startsWith("http://example.com/path");
const changeJson = json => {
// jsonを書き変える
return json;
};
const originalFetch = window.fetch;
window.fetch = (...args) => {
const promise = originalFetch(...args);
const originalThen = promise.then;
promise.then = (onFulfilled) => {
return originalThen.call(promise, (response) => {
const originalJson = response.json;
response.json = () => {
return originalJson.call(response).then(json => {
if (isTarget(response)) {
json = changeJson(json);
}
return json;
});
};
return onFulfilled(response);
});
};
return promise;
};
})();
@tksugimoto
Copy link
Author

TODO: 第2引数 onRejected 対応

Promise.prototype.then() - JavaScript | MDN

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