首页 > 解决方案 > “CORS 政策已阻止访问获取”Chrome 扩展程序错误

问题描述

我正在尝试从 Chrome 扩展程序的后台脚本中的外部 API 获取数据,使用消息传递从内容脚本启动调用并获取结果。我无法控制外部 API。该 API 的文档说使用脚本标签来获取 jsonp 响应,但如果我理解正确,那么在实现以下项目时这无关紧要。我错了吗?

错误:从源“chrome-extension://bunchofchars”获取“https://external-api.com”的访问权限已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“访问权限” -Control-Allow-Origin' 标头存在于请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

关于我做错了什么的任何线索?

背景.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;
  });

内容.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);

})();

标签: javascriptgoogle-chrome-extensioncorsfetch

解决方案


清单版本 3 使用 host_permissions 字段

"host_permissions": ["https://api.com/*"],

推荐阅读