我的请求由于相同的原始策略而失败,但是无论如何,我可以使用webRequest api修改标头在扩展程序中解决此问题吗?
最佳答案
将此添加到您的background.js文件中:
/**
* Force Access-Control-Allow-Origin
*
* Ideally, we'll want to remove this for production,
* and actually set the header server side instead.
*/
chrome.webRequest.onHeadersReceived.addListener(function onHeadersReceived(resp) {
var len = resp.responseHeaders.length;
while(--len) {
if(header.name.toLowerCase() === "access-control-allow-origin") {
resp.responseHeaders[len].value = "*";
break;
}
}
if (len === 0) { //if we didn't find it len will be zero
resp.responseHeaders.push({
'name': 'Access-Control-Allow-Origin',
'value': '*'
});
}
return {responseHeaders: resp.responseHeaders};
}, {
urls: ['*://*.YOU-API-DOMAIN.com/*', '*://localhost/*'],
/*TYPES: "main_frame", "sub_frame", "stylesheet", "script",
"image", "object", "xmlhttprequest", "other" */
types: ['xmlhttprequest']
}, ['blocking', 'responseHeaders']);
并将它们添加到manifest.json权限中:
"webRequest",
"webRequestBlocking"
重新加载扩展名,您应该一切顺利!