javascript - “CORS 政策已阻止访问获取”Chrome 扩展程序错误
问题描述
我正在尝试从 Chrome 扩展程序的后台脚本中的外部 API 获取数据,使用消息传递从内容脚本启动调用并获取结果。我无法控制外部 API。该 API 的文档说使用脚本标签来获取 jsonp 响应,但如果我理解正确,那么在实现以下项目时这无关紧要。我错了吗?
- 在
fetch()
后台脚本中 "\*://\*/"
在清单中的我的权限中(如果我可以让它工作,我会改变它,只是消除这种可能性)- 扩展是“打包”的
错误:从源“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);
})();
解决方案
清单版本 3 使用 host_permissions 字段
"host_permissions": ["https://api.com/*"],
推荐阅读
- c# - Xamarin App Build Error Linking with Net Standard library
- angular - 导入特定模块时,Angular api-prefix 不起作用
- python - 为什么这个使用 openCV 的简单 python 脚本不起作用?
- asynchronous - 在异步 django 通道 websocket 中使用同步 celery 回调
- automated-tests - 如何在 Rest aussured pf RestTemplate 中添加标题
- javascript - Vue-router 异步加载 url
- java - SHA1withRSA NoSuchAlgorithmException
- scala - 如何从整数值创建枚举
- php - SQL问题'where子句'中的未知列'approved'
- android - 在我的设备上启动时看不到 Cardview