modify xhr response
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 chromeLauncher = require('chrome-launcher'); | |
const CDP = require('chrome-remote-interface'); | |
const atob = require('atob'); | |
const btoa = require('btoa'); | |
async function main() { | |
const chrome = await chromeLauncher.launch({ | |
chromeFlags: [ | |
'--window-size=1200,800', | |
'--user-data-dir=/tmp/chrome-testing', | |
'--auto-open-devtools-for-tabs' | |
] | |
}); | |
const protocol = await CDP({port: chrome.port}); | |
const {Runtime, Network} = protocol; | |
await Promise.all([Runtime.enable(), Network.enable()]); | |
//Runtime.consoleAPICalled(({args, type}) => console[type].apply(console, args.map(a => a.value))); | |
await Network.setRequestInterception({ | |
patterns: [{ | |
urlPattern: '*api*', | |
resourceType: 'XHR', | |
interceptionStage: 'HeadersReceived' | |
}] | |
}); | |
Network.requestIntercepted(async ({interceptionId, request}) => { | |
console.log(`Intercepted ${request.url} {interception id: ${interceptionId}}`); | |
const response = await Network.getResponseBodyForInterception({interceptionId}); | |
const bodyData = response.base64Encoded ? atob(response.body) : response.body; | |
const newBody = '{}'//bodyData + `\nconsole.log('Executed modified resource for ${request.url}');`; | |
const newHeaders = [ | |
'Date: ' + (new Date()).toUTCString(), | |
'Connection: closed', | |
'Content-Length: ' + newBody.length, | |
'Content-Type: application/json' | |
]; | |
Network.continueInterceptedRequest({ | |
interceptionId, | |
rawResponse: btoa('HTTP/1.1 500 Internal Server Error' + '\r\n' + newHeaders.join('\r\n') + '\r\n\r\n' + newBody) | |
}); | |
}); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment