拦截ajax请求并修改响应结果的Chrome插件
下面是一个简单的Chrome扩展,它会拦截所有的Ajax请求,并在控制台输出请求的响应内容。
// manifest.json
{
"name": "Ajax Response Modifier",
"version": "1.0",
"description": "Modifies Ajax responses",
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"manifest_version": 2
}
// background.js
chrome.webRequest.onHeadersReceived.addListener(
function(details) {
return {
responseHeaders: details.responseHeaders.map(function(header) {
// Replace Content-Type header to make sure response is parsed as JSON
if (header.name.toLowerCase() === 'content-type' && header.value.indexOf('json') !== -1) {
header.value = 'text/plain;charset=UTF-8';
}
return header;
})
};
},
{
urls: ['<all_urls>'],
types: ['xmlhttprequest']
},
['blocking', 'responseHeaders']
);
chrome.webRequest.onResponseStarted.addListener(
function(details) {
// Read the response as JSON and log it
var reader = new FileReader();
reader.onloadend = function() {
var response = JSON.parse(reader.result);
console.log('Response modified:', response);
};
// Convert the array buffer to a string
reader.readAsText(details.rawResponse);
},
{
urls: ['<all_urls>'],
types: ['xmlhttprequest']
}
);
这个Chrome扩展通过chrome.webRequest
API拦截Ajax请求,并在响应开始时读取原始响应数据。通过FileReader
将ArrayBuffer转换为文本,然后解析并在控制台输出。这个例子只是一个简单的展示如何操作响应内容的示例,实际应用中可能需要根据具体需求修改处理逻辑。
评论已关闭