“访问权限已被CORS政策阻止" Chrome扩展程序错误 [英] 'Access to fetch has been blocked by CORS policy' Chrome extension error
问题描述
我知道这个问题已经被问过很多次了,但是在我看来,我已经做了所有正确的事情,但仍然无法正常工作.
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.
我正在尝试使用Chrome扩展程序的后台脚本从外部API获取数据,并使用消息传递从内容脚本发起调用并获取结果.我无法控制外部API.该API的文档说使用脚本标签来获取jsonp响应,但是如果我理解正确,那么实现以下各项就无关紧要.我错了吗?
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?
- fetch()在后台脚本中
- "*://*/";是我在清单中的权限(如果可以使它正常工作,我将进行更改,只是消除这种可能性)
- 该扩展程序已打包"
错误:从CORS策略阻止从来源"chrome-extension://bunchofchars"访问"https://external-api.com":对预检请求的响应未通过访问控制检查:否访问控制"-Allow-Origin'标头出现在所请求的资源上.如果不透明的响应可以满足您的需求,请将请求的模式设置为"no-cors",以在禁用CORS的情况下获取资源.
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
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
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);
})();
推荐答案
尝试添加 https://api.com/
专门用于manifest.json的权限:
try adding https://api.com/
specifically to manifest.json's permission:
"permissions": ["https://api.com/"]
这篇关于“访问权限已被CORS政策阻止" Chrome扩展程序错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!