javascriptchrome-extension-manifest-v3chrome-declarativenetrequest

chrome declarativeNetRequest append matched url not working


I'm trying to append the matched domain from a declarativeNetRequest rule to the redirect extension page, but I can't seem to be able to get it to work. The redirect is working to my extension page but the matched URL isn't appended.

Here is my code snippet:

  const page = chrome.runtime.getURL('/MyPage.html');
  const RULES = [
  {
    'id': 1,
    'priority': 2,
    action: {type: 'redirect', redirect: {regexSubstitution: page + '#\\0', extensionPath: '/MyPage.html'}},
    'condition': {
      regexFilter: "\w*",
      requestDomains: ["amazon.com"]
    }
  }]

  chrome.declarativeNetRequest.updateDynamicRules({
    removeRuleIds: RULES.map(r => r.id),
    addRules: RULES,
  });

Updated code snippet:

    const page = chrome.runtime.getURL('/MyPage.html');
    const RULES = [
    {
      id: 1,
      priority: 2,
      action: {type: 'redirect', redirect: {regexSubstitution: page + '#\\1' }},
      condition: {
        regexFilter: "https://([^/]+)",
        requestDomains: ["amazon.com"]
      }
    },
    ];
    chrome.declarativeNetRequest.updateDynamicRules({
      removeRuleIds: RULES.map(r => r.id),
      addRules: RULES,
    });

Solution

    1. Remove , extensionPath: '/MyPage.html' as you already have a substitution
    2. Replace \w* with ://([^/]+) to capture dots and dashes in the domain name, also note that inside regexp strings you need to use an escaped backslash \\ not \ while there's no need to escape the forward slash /.
    3. replace #\\0 with #\\1 to get the parenthesized group of the above regexp.