1

Everytime I make a call to another website in my background script with fetch(), I receive this error: Access to XMLHttpRequest at 'http://127.0.0.1:8080/api/allowedDomains' from origin 'chrome-extension://ngaahahncefaccijfgplkmbghbbolonk' has been blocked by CORS policy

Nightloewe
  • 918
  • 1
  • 14
  • 24
  • See https://www.chromium.org/Home/chromium-security/extension-content-script-fetches – sideshowbarker Feb 29 '20 at 07:49
  • 3
    This question is not a duplicate and should be re-opened. It doesnt have to do with all those answers above! – avalanche1 Apr 22 '20 at 16:24
  • 1
    Once I changed the localhost value specified in "host_permissions" (I'm using manifest 3) from `"*://localhost:8080/*"` to `"http://localhost:8080/*"`, I stopped getting errors – Austin May 02 '22 at 02:12

1 Answers1

0

EDIT:

As @avalanche1 pointed out in the comments, extension scripts running in the extension security origin are not subject to the same CORS restrictions as web pages and extension content scripts are. According to Chrome's documentation on the subject:

By adding hosts or host match patterns (or both) to the permissions section of the manifest file, the extension can request access to remote servers outside of its origin.

{
  "name": "My extension",
  ...
  "permissions": [
    "https://www.google.com/"
  ],
  ...
}

ORIGINAL ANSWER:

See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS for more info on why this happens:

For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was loaded from, unless the response from other origins includes the right CORS headers.

Long story short is that you can't make requests to another website unless that website gives you permission.

If you control the website you are sending requests to (since it is localhost I'm thinking that may be the case in this instance), you can configure the website to respond with the correct headers (see the above link for specifics).

If you don't control the website, then unless the party that does gives you a way to programmatically consume it, there is no way to request it from JS.

  • 3
    This is incorrect because background scripts are **by design** allowed to do a request to any url and bypass CORS. Although, this seems not to be the case after I've updated to Chrome 81. Still don't know the reason... – avalanche1 Apr 22 '20 at 16:20