I'm trying to write a chrome extension which intercepts network traffic and modify the data.
I would appreciate if someone can tell me exactly which API I should use for this and where I can find the documentation.
Make use of the webRequest API and have a look at their events.
Create a manifest with permissions activeTab
to get permissions for the current tab on which you are on, and the url pattern you wish the extension to be enabled for. The webRequestBlocking
permission needs to be set specifically for blocking and modifying traffic.
{
"manifest_version": 2,
"name": "network intercepter",
"description": "intercept/modify/block data",
"version": "1.0",
"background": {
"scripts": ["background.js"]
},
"host_permissions": [
"https://*.google.com/*"
],
"permissions": [
"activeTab",
"webRequest",
"webRequestBlocking"
]
}
Create a background script and start adding webRequest listener based on which actions you want to perform. This was useful for me when making those choices.
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"]);
Visit chrome://extensions and open the background page, and go to its console. Then visit https://google.com normally, you will see that all images are changed to their new location, the XHR's are blocked, and the script resources have their User Agent changed, and in the background console you will find the requests that were made.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With