'Access to fetch has been blocked by CORS policy' Chrome扩展程序错误



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

  • fetch()在后台脚本中
  • "*://*/"在清单中属于我的权限范围(如果我能让它工作,我会更改它,只是消除这种可能性(
  • 扩展名已"打包">

错误:访问"获取https://external-api.com"源自"铬-extension://bunchofchars'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在"access control Allow Origin"标头。如果不透明响应满足您的需求,请将请求的模式设置为"无cors",以在禁用cors的情况下获取资源。

我做错了什么?

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);
})();

Manifest版本3使用host_permissions字段

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

也许你的扩展只允许在这个特定的网站上读取和修改。

让扩展读取并更改站点数据

  • 单击扩展时:此设置仅允许扩展在单击扩展时访问打开的选项卡或窗口中的当前网站。如果关闭选项卡或窗口,则必须单击扩展才能再次打开它
  • 在[当前站点]上:允许扩展自动读取和更改当前站点上的数据
  • 在所有站点上:允许扩展自动读取和更改所有站点上的数据

尝试更改为最后一个选项。这应该会改变CORS政策。

理想情况下,必须在服务器端通过添加特定的源来解决cors问题。这是因为所有现代浏览器(如chrome(都会阻止来自同一台机器的请求。

然而,在这种情况下,请尝试使用以下附加的提取参数:

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
});

相关内容

最新更新