Created
June 10, 2017 03:21
-
-
Save tksugimoto/2b2a32ffe27b3142f5d764ee1085c3df to your computer and use it in GitHub Desktop.
JavaScript fetch APIを書き換えて通信内容を変更する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(() => { | |
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; | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TODO: 第2引数
onRejected
対応Promise.prototype.then() - JavaScript | MDN