'Access to fetch has been blocked by CORS policy' Chrome extension error

风格不统一 提交于 2021-01-07 03:13:15

问题


I know this has been asked many times, but it seems to me that I've done all the right things and still can't get it working.

I am trying to get data from an external API from the background script of my Chrome extension, using messaging to initiate the call from the content script and get the results. I have no control over the external API. The documentation from that API says to use script tags to get a jsonp response, but if I understand correctly, that shouldn't matter when the below items are implemented. Am I wrong?

  • the fetch() is in the background script
  • "*://*/" is in my permissions in the manifest (I will change that if I can get this to work, just eliminating that possibility)
  • The extension is 'packed'

Error: Access to fetch at 'https://external-api.com' from origin 'chrome-extension://bunchofchars' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Any clue as to what I'm doing wrong?

background.js

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
      fetch('https://api.com/' + request.user + 'restofurl',
          {
            method: 'get',
            headers: {'Content-Type':'application/json'}
          })
//          .then(response => parseResults(response.results))
          .then(response => sendResponse({result: response.results}))
//          .catch(error => ...)
      return true;
  });

content.js

(() => {
    function foo() {

        var parent = document.getElementById('someId');
        var username = parent.getElementsByTagName('a')[6].innerHTML;
        chrome.runtime.sendMessage({user: username}, function(response) {
            console.log(response.result);
        });
    window.addEventListener('load', foo);

})();

回答1:


try adding https://api.com/ specifically to manifest.json's permission:

"permissions": ["https://api.com/"]



回答2:


Ideally, cors issue must be resolved on the server-side by adding specific origins. This is because all modern browsers such as chrome block the requests originating from the same machine.

In this case, however, please try to use additional fetch parameters as follows:

fetch(url, {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'no-cors', // no-cors, *cors, same-origin

headers: {
  //'Content-Type': 'application/json'
  // 'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify(data) // body data type must match "Content-Type" header
});


来源:https://stackoverflow.com/questions/64732755/access-to-fetch-has-been-blocked-by-cors-policy-chrome-extension-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!