目录
功能
演示
源代码下载
manifest.json
devtools.html
devtools.js
background.js
功能
拦截任意打开页面的请求信息,包括:URL,参数,请求方式method, 返回status,返回体大小,返回原始内容
演示
源代码下载
https://download.csdn.net/download/wodeyijia911/88180871
manifest.json
{
"name": "chromepulgin",
"version": "1.0.0",
"minimum_chrome_version": "10.0",
"description": "chrome devtools",
"manifest_version": 2,
// devtools页面入口,注意只能指向一个HTML文件,不能是JS文件
"devtools_page": "devtools.html",
"content_scripts": [
{
"matches": ["*://*/*"],
"css": [],
"js": ["scripts/axios.min.js","scripts/vue.min.js", "content_scripts.js"]
}
],
"background": {
"scripts": [
"scripts/background.js" //指定了scripts属性,则Chrome会在扩展启动时自动创建一个包含所有指定脚本的页面
],
"persistent": true //定义了常驻后台的方式——当其值为true时,表示扩展将一直在后台运行,无论其是否正在工作
},
"permissions": [
"webRequest",
"webRequestBlocking",
"storage",
"tabs",
"http://*/*",
"https://*/*",
"contextMenus",
"chrome://favicon/"
],
"content_security_policy": "style-src 'self' 'unsafe-inline' https://unpkg.com;script-src 'self' 'unsafe-eval' https://cdn.bootcss.com;object-src 'self' ;",
"icons": {
},
"browser_action": {
// "default_icon": "img/chrome01.png",
// "default_popup": "popup.html",
// "default_title": "magic"
}
}
devtools.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="scripts/jquery-3.5.1.min.js"></script>
<script type="text/javascript" src="js/devtools.js"></script>
</body>
</html>
devtools.js
ps: devtools.js 类似popup.js, 可以直接调用background.js中的函数
chrome.webRequest.*API 均不能获取请求返回的内容。
const CD = chrome.devtools;
// Chrome DevTools Extension中不能使用console.log
const log = (...params) => CD.inspectedWindow.eval(`console.log(...${JSON.stringify(params)})`);
log('devtools.js log........');
chrome.devtools.network.onRequestFinished.addListener(
async (...args) => {
try {
const [{
// 请求的类型,查询参数,以及url
request: { method, queryString, url },
response: { bodySize, status },
// 该方法可用于获取响应体
getContent,
}] = args;
log(method, queryString, url);
log(bodySize, status);
// 将callback转为await promise
// warn: content在getContent回调函数中,而不是getContent的返回值
const content = await new Promise((res, rej) => getContent(res));
log('response= '+content);
// 调用background.js中的函数
var bg = chrome.extension.getBackgroundPage();
bg.sendRequest(url);
} catch (err) {
log(err.stack || err.toString());
}
});
background.js
document.scripts[0].src="axios.min.js"
function addScript(url){
var script = document.createElement('script');
script.setAttribute('type','text/javascript');
script.setAttribute('src',url);
document.getElementsByTagName('head')[0].appendChild(script);
}
addScript("scripts/axios.min.js")
function sendRequest(args){
console.log("bg sendRequest");
this.axios({
method: args.method,
url: args.url,
data: args.data,
headers:args.headers
}).then(resp => { //请求成功
console.log("sendRequest:"+resp);
}).catch(error => { //请求失败
console.log(error);
}).then(() => { //() => {} 相当于 function(){}
console.log("不管怎么样都要执行"); //必须执行的代码,相当于finnally
})
}