前言
由于一些原因,研究了下chrome如果去捕获http请求的response结果,遂记录下来。
// manifest.json
{
"manifest_version": 2,
"name": "<插件名称>",
"version": "1.0.0",
"description": "zhiniao extension",
// 会一直常驻的后台JS或后台页面
"background": {
"scripts": [
"js/jquery.min.js",
"js/background.js"
]
},
// 权限申请
"permissions": [
"tabs",
"activeTab",
"contextMenus",
"storage",
"webRequest",
"debugger",
"<all_urls>"
],
// 需要直接注入页面的JS
"content_scripts": [
{
"js": [
"js/jquery.min.js",
"js/content-script.js"
],
// "<all_urls>" 表示匹配所有地址
"matches": [
"http://*/*",
"https://*/*"
],
// 代码注入的时间,可选值: "document_start", "document_end", or "document_idle",最后一个表示页面空闲时,默认document_idle
"run_at": "document_start"
}
],
// 普通页面能够直接访问的插件资源列表,如果不设置是无法直接访问的
"web_accessible_resources": ["js/inject.js"],
// 插件的图标
"icons": {
"16": "imgs/icon.png",
"32": "imgs/icon.png",
"64": "imgs/icon.png",
"128": "imgs/icon.png"
},
"omnibox": {
"keyword": "<keyword>"
},
// devtools页面入口,注意只能指向一个HTML文件,不能是JS文件
"devtools_page": "devtools.html"
}
由于Chrome DevTools extensions不支持console.log,所以使用以下方式来进行console.log的操作:
const log = (...args) =>
chrome.devtools.inspectedWindow.eval(`
console.log(...${JSON.stringify(args)});
`)
目前chrome.devtools方法只适用于devtools和panel中
// 注册回调,每一个http请求响应后,都触发该回调
chrome.devtools.network.onRequestFinished.addListener(async (...args) => {
try {
const [{
// 请求的类型,查询参数,以及url
request: { method, queryString, url },
// 该方法可用于获取响应体
getContent,
}] = args;
log(method, queryString, url);
// 将callback转为await promise
// warn: content在getContent回调函数中,而不是getContent的返回值
const content = await new Promise((res, rej) => getContent(res));
log(content);
} catch (err) {
log(err.stack || err.toString());
}
});