Google chrome extension 我如何解决访问控制问题允许扩展中的源代码

Google chrome extension 我如何解决访问控制问题允许扩展中的源代码,google-chrome-extension,Google Chrome Extension,我的请求因同源策略而失败,但我是否可以在扩展中使用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.onHead

我的请求因同源策略而失败,但我是否可以在扩展中使用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"

重新加载分机,您就可以开始了

出于开发目的,您还可以使用
--disable web security
Chrome标志。如果请求是由您的扩展名生成的,您需要将URL添加到清单文件的
权限部分。但这不意味着所有网站都可以进行跨源请求吗?国旗不酷:是的,这就是我为什么说“发展目的”。关于“权限”键:否,只有您的扩展才能发出跨源请求。您当前的解决方案允许任何人对URL列表进行跨源请求。