2

由于相同的来源策略,我的请求失败了,但是无论如何我可以在扩展中使用 webRequest api 修改标头来解决这个问题吗?

4

1 回答 1

7

将此添加到您的 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(resp.responseHeaders[len].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"

重新加载扩展,你应该很高兴!

于 2012-12-11T11:35:42.000 回答