0

I am having trouble getting a chrome extension that redirects REST API calls from one host to another. Specifically, trying to redirect POSTs that go to https://api.old.com/endpoint to get redirected to https://api.new.com/newapi.

The onRuleMatchedDebug never gets called here, and I have not found any solutions or example on the web so far. Anyone have any ideas?

manifest.json:

{
  "name": "Foo",
  "version": "1.0",
  "manifest_version": 3,
  "declarative_net_request": {
    "rule_resources": [
      {
        "id": "ruleset_1",
        "enabled": true,
        "path": "rules_1.json"
      }
    ]
  },
  "permissions": [
    "declarativeNetRequest",
    "declarativeNetRequestFeedback",
    "declarativeNetRequestWithHostAccess"
  ],
  "background": {
    "service_worker": "serviceWorker.js"
  },
  "host_permissions": ["https://api.old.com/*", "https://api.new.com/*"]
}

rules_1.json:

[
  {
    "id": 1,
    "action": {
      "type": "redirect",
      "redirect": {
        "url": "https://api.new.com/newapi"
      }
    },
    "condition": {
      "urlFilter": "https://api.old.com/endpoint",
      "resourceTypes": ["xmlhttprequest"],
      "requestMethods": ["post"]
    }
  }
]

Service worker:

'use strict';

chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((e) => {
  const msg = `Navigation to ${e.request.url} redirected on tab ${e.request.tabId}.`;
  console.log(msg, e);
});

console.log('Service worker started!.');
user910046
  • 308
  • 4
  • 14
  • Assuming you look at the [correct devtools console](/a/10258029), the explanations are: 1) a bug in the browser, 2) a mistake in your serviceWorker.js 3) urlFilter/type/method doesn't match the actual request and 4) the site is protected in ExtensionSettings -> runtime_blocked_hosts in `chrome://policy` – wOxxOm Jul 18 '23 at 20:30
  • Could any CSP settings affect this perhaps? If I change the action type to block then the calls are properly blocked and the service woker onRuleMatchedDebug prints as well. – user910046 Jul 18 '23 at 21:31
  • @wOxxOm So I figured it out, it was my host_permissions. The actual url is https://a.b.c.d.e.foo.com/api/baz and having https://a.b.c.d.e.foo.com/* as my host permission was the problem - if I change it to https:/*.foo.com/* it suddenly works, even if the full URL is correct. – user910046 Jul 18 '23 at 22:55
  • @wOxxOm On a different note, now CSP is blocking things because of `connect-src` being set, is there a way around it? Weird that an extension redirect is still being affected by CSP, makes things much harder. – user910046 Jul 18 '23 at 22:57
  • CSP being applied is the correct behavior. You can modify the CSP header separately. As for the URL, it's either a bug in the browser or there was a redirect, which should be seen in devtools. – wOxxOm Jul 19 '23 at 04:10

0 Answers0