oti*_*i10 28 javascript google-chrome-extension
这似乎是困难的问题(或不可能?).我想通过观看Chrome扩展程序后台脚本来获取并阅读由浏览器中的HTTP请求引起的HTTP响应.我们可以通过这种方式获得HTTP Request Body
chrome.webRequest.onBeforeRequest.addListener(function(data){
// data contains request_body
},{'urls':[]},['requestBody']);
Run Code Online (Sandbox Code Playgroud)
我还检查了这些stackoverflows
有没有聪明的方法来获取Chrome扩展中的HTTP响应体?
小智 20
我找不到比这更好的方式了.
anwser告诉如何获取 响应标头并显示在另一个页面中.但是响应obj中没有正文信息(请参阅event-responseReceived).如果你想获得 没有其他页面的响应主体,试试这个.
var currentTab;
var version = "1.0";
chrome.tabs.query( //get current Tab
{
currentWindow: true,
active: true
},
function(tabArray) {
currentTab = tabArray[0];
chrome.debugger.attach({ //debug at current tab
tabId: currentTab.id
}, version, onAttach.bind(null, currentTab.id));
}
)
function onAttach(tabId) {
chrome.debugger.sendCommand({ //first enable the Network
tabId: tabId
}, "Network.enable");
chrome.debugger.onEvent.addListener(allEventHandler);
}
function allEventHandler(debuggeeId, message, params) {
if (currentTab.id != debuggeeId.tabId) {
return;
}
if (message == "Network.responseReceived") { //response return
chrome.debugger.sendCommand({
tabId: debuggeeId.tabId
}, "Network.getResponseBody", {
"requestId": params.requestId
}, function(response) {
// you get the response body here!
// you can close the debugger tips by:
chrome.debugger.detach(debuggeeId);
});
}
}
Run Code Online (Sandbox Code Playgroud)
我认为它对我来说足够有用,你可以chrome.debugger.detach(debuggeeId)用来关闭丑陋的小费.
抱歉,mabye没有帮助...... ^ ^
小智 8
要获取 XHR响应正文,您可以按照此答案中的说明进行操作。
要获取 FETCH响应正文,您可以查看本文中的解决方案 3以及此答案。两者都无需使用 chrome.debugger 即可获取响应正文。
简而言之,您需要使用与 XHR 请求相同的方法将以下函数从内容脚本注入到页面中。
const constantMock = window.fetch;
window.fetch = function() {
return new Promise((resolve, reject) => {
constantMock.apply(this, arguments)
.then((response) => {
if (response) {
response.clone().json() //the response body is a readablestream, which can only be read once. That's why we make a clone here and work with the clone
.then( (json) => {
console.log(json);
//Do whatever you want with the json
resolve(response);
})
.catch((error) => {
console.log(error);
reject(response);
})
}
else {
console.log(arguments);
console.log('Undefined Response!');
reject(response);
}
})
.catch((error) => {
console.log(error);
reject(response);
})
})
}
Run Code Online (Sandbox Code Playgroud)
如果response.clone().json()不起作用,你可以尝试response.clone().text()
现在在 Chrome 开发者工具扩展中有一种方法,示例代码可以在这里看到:博客文章。
简而言之,这是对他的示例代码的改编:
chrome.devtools.network.onRequestFinished.addListener(request => {
request.getContent((body) => {
if (request.request && request.request.url) {
if (request.request.url.includes('facebook.com')) {
//continue with custom code
var bodyObj = JSON.parse(body);//etc.
}
}
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19282 次 |
| 最近记录: |