Search code examples
javascriptregexgoogle-chrome-extensionchrome-extension-manifest-v3

Chrome Extension : Redirecting with regexSubstitution but keeping path if existing


Im trying to create a extension that automaticly changes the url from amazon.com to amazon.de while keeping the path if a path is given using chrome.declarativeNetRequest.

https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/

I tried multiple things and the following one is almost working. The problem is the URL Changes to https://www.amazon.de%241/ and not to https://www.amazon.de/. Same thing happens if I enter the link with a given path. It always redirect to https://www.amazon.de%241/

in the manifest.json file i added following line

manifest.json

[...]
 "declarative_net_request": {
        "rule_resources": [{
            "id": "ruleset_1",
            "enabled": true,
            "path": "rule.json"
        }]
    },
    "permissions": [
        "declarativeNetRequest",
        "declarativeNetRequestFeedback"
    ],

[...]

rule.json

[
   {
      "id":1,
      "priority":1,
      "action":{
         "type":"redirect",
         "redirect":{
            "regexSubstitution":"https://www.amazon.de$1"
         }
      },
      "condition":{
         "regexFilter":"^https://www\\.amazon\\.com(/.*)?$",
         "resourceTypes":[
            "main_frame"
         ]
      }
   }
]

Solution

  • To fix it replace $1 with \1 as shown in the documentation.

    A much more performant alternative is to use urlFilter + transform:

    [{
      "id": 1,
      "condition": {
        "urlFilter": "|https://www.amazon.com/",
        "resourceTypes": ["main_frame"]
      },
      "action": {
        "type": "redirect",
        "redirect": {
          "transform": {
            "host": "www.amazon.de"
          }
        }
      }
    }]