我正在尝试从WebExtension内容脚本进行HTTP GET AJAX调用。由于正确设置了CORS响应标头,因此允许当前标签进行该呼叫。
但是,使用Firefox浏览器工具箱,尝试拨打该电话时,我会看到此错误:
跨源请求被阻止:同源策略禁止读取[URL]上的远程资源(原因:不能添加CORS标头“ Origin”)。
Internet上没有太多有关此错误消息的资源。从this not very detailed documentation看,问题似乎出在请求中,而缺少Origin
标头。
我尝试手动进行设置,但是我当然知道:
试图设置禁止的标头被拒绝:起源
如何拨打GET电话?
请注意,完全相同的代码可在Chromium WebExtension中使用。
manifest.json
{
"description": "Adds a solid red border to all webpages matching mozilla.org. See https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Examples#borderify",
"manifest_version": 2,
"name": "Borderify",
"version": "1.0",
"homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/borderify",
"icons": {
"48": "icons/border-48.png"
},
"content_scripts": [
{
"matches": ["*://stackoverflow.com/*"],
"js": ["node_modules/jquery/dist/jquery.min.js", "borderify.js"]
}
]
}
borderify.js
// asset present on SO
const url = 'https://www.gravatar.com/avatar/69ae657aa40c6c777aa2f391a63f327f?s=32&d=identicon&r=PG'
$.ajax({
url,
cache: false,
type: 'GET',
success: (a) => {
console.log('in');
console.log(a);
},
error: (a) => {
console.log('woops!');
console.log(a);
},
});
yarn add jquery
控制台:
woops!
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.gravatar.com/avatar/69ae657aa40c6c777aa2f391a63f327f?s=32&d=identicon&r=PG&_=1561714948375. (Reason: CORS header ‘Origin’ cannot be added).