如何在扩展中解决Access-Control-Allow-Origin问题

时间:2012-12-11 11:35:42

标签: google-chrome-extension

我的请求由于相同的原始策略而失败,但无论如何我可以使用webRequest api修改标题来解决这个问题吗?

1 个答案:

答案 0 :(得分:6)

将此添加到您的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"

重新加载扩展,你应该好好去!