HTTP request interception and modification in browser extension

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
Development and maintenance of all types of websites:
Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:
Development stages
Latest works
  • image_website-b2b-advance_0.png
    B2B ADVANCE company website development
    1212
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    852
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    822
  • image_bitrix-bitrix-24-1c_fixper_448_0.png
    Website development for FIXPER company
    815

Implementing HTTP Request Interception and Modification in Browser Extension

HTTP request interception is one of the most powerful capabilities of extensions. Ad blockers, VPN extensions, proxy tools, header injectors — they all build on chrome.webRequest (MV2) or chrome.declarativeNetRequest (MV3). The transition to MV3 fundamentally changed the approach.

MV3: declarativeNetRequest

In Manifest V3, dynamic request modification is replaced by declarative rules. The browser applies rules itself, without running extension JS code. This is faster and safer, but less flexible.

{
  "manifest_version": 3,
  "permissions": ["declarativeNetRequest", "declarativeNetRequestWithHostAccess"],
  "host_permissions": ["<all_urls>"],
  "declarative_net_request": {
    "rule_resources": [
      {
        "id": "static-rules",
        "enabled": true,
        "path": "rules/static.json"
      }
    ]
  }
}

Static Rules

File rules/static.json contains an array of rules applied permanently:

[
  {
    "id": 1,
    "priority": 1,
    "action": { "type": "block" },
    "condition": {
      "urlFilter": "||analytics.example.com^",
      "resourceTypes": ["script", "xmlhttprequest", "image"]
    }
  },
  {
    "id": 2,
    "priority": 2,
    "action": {
      "type": "modifyHeaders",
      "requestHeaders": [
        { "header": "X-Custom-Token", "operation": "set", "value": "my-token" },
        { "header": "Referer", "operation": "remove" }
      ]
    },
    "condition": {
      "urlFilter": "https://api.internal.corp/*",
      "resourceTypes": ["xmlhttprequest"]
    }
  },
  {
    "id": 3,
    "priority": 1,
    "action": {
      "type": "redirect",
      "redirect": { "regexSubstitution": "https://cdn.example.com\\1" }
    },
    "condition": {
      "regexFilter": "^https://slow-cdn\\.com(.*)",
      "resourceTypes": ["image", "media", "font"]
    }
  }
]

Limits: maximum 30,000 static rules total across all files, 5,000 enabled rules at once (can be changed dynamically).

Dynamic Rules from Service Worker

Rules can be added and removed at runtime:

// background/sw.js
async function blockDomain(domain) {
  const existingRules = await chrome.declarativeNetRequest.getDynamicRules();
  const maxId = existingRules.reduce((max, r) => Math.max(max, r.id), 0);

  await chrome.declarativeNetRequest.updateDynamicRules({
    addRules: [{
      id: maxId + 1,
      priority: 10,
      action: { type: 'block' },
      condition: {
        urlFilter: `||${domain}^`,
        resourceTypes: [
          'main_frame', 'sub_frame', 'script', 'stylesheet',
          'image', 'xmlhttprequest', 'other'
        ]
      }
    }],
    removeRuleIds: []
  });
}

async function unblockDomain(domain) {
  const rules = await chrome.declarativeNetRequest.getDynamicRules();
  const toRemove = rules
    .filter(r => r.condition.urlFilter === `||${domain}^`)
    .map(r => r.id);

  if (toRemove.length > 0) {
    await chrome.declarativeNetRequest.updateDynamicRules({
      addRules: [],
      removeRuleIds: toRemove
    });
  }
}

// Header modification with dynamic value
async function setAuthHeader(apiUrl, token) {
  const rules = await chrome.declarativeNetRequest.getDynamicRules();
  const existingRule = rules.find(r =>
    r.condition.urlFilter === apiUrl && r.action.type === 'modifyHeaders'
  );

  const newRule = {
    id: existingRule?.id ?? (rules.reduce((m, r) => Math.max(m, r.id), 0) + 1),
    priority: 5,
    action: {
      type: 'modifyHeaders',
      requestHeaders: [
        { header: 'Authorization', operation: 'set', value: `Bearer ${token}` }
      ]
    },
    condition: {
      urlFilter: apiUrl,
      resourceTypes: ['xmlhttprequest', 'fetch']
    }
  };

  await chrome.declarativeNetRequest.updateDynamicRules({
    addRules: [newRule],
    removeRuleIds: existingRule ? [existingRule.id] : []
  });
}

Request Observation: chrome.webRequest (MV2 only)

In MV2 you could intercept requests synchronously and modify them in JS. In MV3, chrome.webRequest is available only in observation mode (without blocking):

// MV2 or MV3 (read-only, without blocking)
chrome.webRequest.onCompleted.addListener(
  (details) => {
    if (details.statusCode >= 400) {
      logFailedRequest({
        url: details.url,
        status: details.statusCode,
        tabId: details.tabId,
        timestamp: details.timeStamp
      });
    }
  },
  { urls: ['https://api.your-service.com/*'] },
  ['responseHeaders']
);

chrome.webRequest.onBeforeRequest.addListener(
  (details) => {
    // In MV3 — observation only, without blocking
    analytics.track('request', {
      url: new URL(details.url).pathname,
      method: details.method,
      tabId: details.tabId
    });
  },
  { urls: ['<all_urls>'], types: ['xmlhttprequest'] }
);

Request Redirection via declarativeNetRequest

Complex redirects with substitution:

// Redirect requests from staging to production
await chrome.declarativeNetRequest.updateDynamicRules({
  addRules: [{
    id: 100,
    priority: 1,
    action: {
      type: 'redirect',
      redirect: {
        regexSubstitution: 'https://api.production.com\\1'
      }
    },
    condition: {
      regexFilter: '^https://api\\.staging\\.com(.*)',
      resourceTypes: ['xmlhttprequest', 'fetch']
    }
  }],
  removeRuleIds: []
});

Response Header Injection

With declarativeNetRequestWithHostAccess permission, you can modify response headers — for example, remove CORS restrictions for development:

await chrome.declarativeNetRequest.updateDynamicRules({
  addRules: [{
    id: 200,
    priority: 1,
    action: {
      type: 'modifyHeaders',
      responseHeaders: [
        { header: 'Access-Control-Allow-Origin', operation: 'set', value: '*' },
        { header: 'Access-Control-Allow-Methods', operation: 'set', value: 'GET, POST, PUT, DELETE' },
        { header: 'X-Frame-Options', operation: 'remove' }
      ]
    },
    condition: {
      urlFilter: 'https://api.internal.corp/*',
      resourceTypes: ['xmlhttprequest']
    }
  }],
  removeRuleIds: []
});

Rule Debugging

// Check which rules were applied to recent requests
const matched = await chrome.declarativeNetRequest.getMatchedRules({
  tabId: tab.id,
  minTimeStamp: Date.now() - 60000
});
console.log('Applied rules:', matched.rulesMatchedInfo);

// Check if a rule will work for a specific URL
const result = await chrome.declarativeNetRequest.testMatchOutcome({
  url: 'https://analytics.example.com/track',
  type: 'xmlhttprequest',
  method: 'GET',
  tabId: -1,
  initiator: 'https://example.com'
});
console.log('Result:', result.matchedRule); // null or rule object

MV3 Limitations and Workarounds

Cannot modify request body via declarativeNetRequest. For this you need a content script that intercepts fetch/XMLHttpRequest via monkey-patching in world: 'MAIN':

// content script with world: 'MAIN'
const originalFetch = window.fetch;
window.fetch = async function(input, init = {}) {
  const url = typeof input === 'string' ? input : input.url;

  if (url.includes('api.target.com')) {
    init.headers = {
      ...init.headers,
      'X-Injected-Header': 'value',
    };

    // Modify body
    if (init.body) {
      const body = JSON.parse(init.body);
      body.extraField = 'injected';
      init.body = JSON.stringify(body);
    }
  }

  return originalFetch.call(this, input, init);
};

This works, but has a limitation: monkey-patching doesn't affect requests from page worker threads and doesn't intercept WebSocket.

For extensions that need full control over traffic (corporate proxies, security tools), MV2 is still available under corporate policy in Chrome, but won't be supported in the public Chrome Web Store.