我试图编写一个镀铬扩展程序来拦截网络流量并修改数据。
如果有人能告诉我我应该使用哪种API以及在哪里可以找到文档,我将不胜感激。
答案 0 :(得分:5)
使用webRequest API并查看他们的events。
创建一个包含权限activeTab
的清单,以获取您所在的当前标签的权限,以及您希望为其启用扩展程序的url pattern。需要专门设置webRequestBlocking
权限以阻止和修改流量。
{
"manifest_version": 2,
"name": "network intercepter",
"description": "intercept/modify/block data",
"version": "1.0",
"background": {
"scripts": ["background.js"]
},
"permissions": [
"activeTab",
"https://*.google.com/*",
"webRequest",
"webRequestBlocking"
]
}
创建后台脚本并根据您要执行的操作开始添加webRequest侦听器。 This在做出这些选择时对我很有用。
var onBeforeSendHeadersListener = function(details) {
// view request + headers to be send
console.log(details);
// block XMLHttpRequests by returning object with key "cancel"
if (details.type == "xmlhttprequest") {
return {
cancel: true
};
}
// modify the user agent of all script resources by changing the requestHeaders and then return an object with key "requestHeaders"
if (details.type == "script") {
for (var i = 0; i < details.requestHeaders.length; i++) {
if (details.requestHeaders[i].name == "User-Agent") {
details.requestHeaders[i].value = "I'm not a bot";
}
}
return {
"requestHeaders": details.requestHeaders
};
}
}
var onBeforeRequestListener = function(details) {
// all images will now be loaded from this location instead
// CAREFUL! CROSS ORIGIN REQUESTS WILL NOT BE BLOCKED WITH CHROME EXTENSIONS
if (details.type == "image") {
return {
"redirectUrl": "https://foo.bar/image.jpg"
};
}
}
chrome.webRequest.onBeforeSendHeaders.addListener(onBeforeSendHeadersListener, {
urls: ["https://*.google.com/*"]
}, ["requestHeaders", "blocking"]);
chrome.webRequest.onBeforeRequest.addListener(onBeforeRequestListener, {
urls: ["https://*.google.com/*"]
}, ["requestBody", "blocking"]);
访问chrome:// extensions并打开后台页面,然后转到其控制台。然后通常访问https://google.com,您将看到所有图像都更改为新位置,XHR被阻止,脚本资源的用户代理已更改,在后台控制台中您将看到所做的请求