我知道这已经被问过很多次了,但在我看来,我已经做了所有正确的事情,但仍然无法让它发挥作用。
我正在尝试从 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;
});
Run Code Online (Sandbox Code Playgroud)
内容.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);
})();
Run Code Online (Sandbox Code Playgroud)