我正在制作一个Chrome扩展,从我自己的服务器中提取数据。它一次使用大约4个httprequest,但有时我得到控制台错误如下:
XMLHttpRequest cannot load http://apps.radionsm.lv/apps/system/index.php?request=now. Origin chrome-extension://egkddfmbidfobhchndockbhjancbpfkd is not allowed by Access-Control-Allow-Origin.
为每个人有时没有。
如果我发送header('Access-Control-Allow-Origin: *');
会修复它吗?
您正在尝试跨域资源共享(CORS)。坏消息是,如果没有服务器作为中间人,就没有办法在正常的网页上做到这一点。好消息是,在chrome扩展,你可以请求权限访问任何url的你想要的。把这样的东西放进你的舱单里。json文件。
允许连接到您的站点:
"permissions": [
"http://*.radionsm.lv/"
],
允许连接到任何站点:
"permissions": [
"http://*/"
],
当用户安装您的扩展时,chrome将在完成安装之前在对话框中通知他们所需的权限。
Chrome扩展在跨域XHR请求时有两种"模式":
1)如果域在清单的"权限"部分。json文件-请求没有"Origin"头,它总是成功的。
2)如果域不在"权限"-请求包括一个"起源"头值"chrome-extension://…"这表明请求是CORS请求,并且响应必须具有有效的Access-Control-Allow-Origin标头才能成功。
您需要在manifest.json中设置权限:
"permissions": [
"https://example.com/" // if you need a particular site
"<all_urls>" // if you need any site (this will incur
// manual review process in Chrome web store, mind you)
],
请注意,由于Chrome 85 extn内容脚本受到相同的CORS策略作为香草web请求。这意味着在extn中进行跨站请求的唯一方法是在后台脚本中获取并将结果传递给内容脚本:
// Old content script, making a cross-origin fetch:
var itemId = 12345;
var url = "https://another-site.com/price-query?itemId=" +
encodeURIComponent(request.itemId);
fetch(url)
.then(response => response.text())
.then(text => parsePrice(text))
.then(price => ...)
.catch(error => ...)
// New content script, asking its background page to fetch the data instead:
chrome.runtime.sendMessage(
{contentScriptQuery: "queryPrice", itemId: 12345},
price => ...);
// New extension background page, fetching from a known URL and relaying data:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.contentScriptQuery === "queryPrice") {
var url = "https://another-site.com/price-query?itemId=" +
encodeURIComponent(request.itemId);
fetch(url)
.then(response => response.text())
.then(text => parsePrice(text))
.then(price => sendResponse(price))
.catch(error => ...)
return true; // Will respond asynchronously.
}
});
Manifest V3: change permissions
to host_permissions
:
"host_permissions": [
"http://*/"
],
在google上花了几天时间,我终于找到了这个解决方案。
- 如果你正在使用Spring引导,并且你正在编写自己的CORSFilter类,并且你正在维护安全java配置文件,不要在Spring中编写多个CORS来注册。
在我的情况下,我有CORSFilter java类以及以下代码。http.cors(withDefaults())
//删除这个,因为我已经注册了CORS