2

My requests fail because of the same origin policy, but is there anyway I can work around this in extensions using the webRequest api to modify the headers?

3
  • For development purposes you can also use the --disable-web-security Chrome flag. If the request is generated by your extension, you need to add the URL to the permissions section of your manifest file. Commented Dec 11, 2012 at 13:12
  • But wouldn't that mean all websites can do cross-origin requests? Not cool Commented Dec 11, 2012 at 16:37
  • About the flag: Yes, that's why I said "development purposes". About the "permissions" key: No, only your extension will be able to make the cross-origin requests. Your current solution allows anyone to make cross-origin requests to the list of URLs. Commented Dec 11, 2012 at 16:39

1 Answer 1

7

Add this to your background.js file:

/** * 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']); 

And also add these to your manifest.json permissions:

"webRequest", "webRequestBlocking" 

Reload extension and you should be good to go!

Sign up to request clarification or add additional context in comments.

1 Comment

Devin, header is undefined in code. it should be resp.responseHeaders[len].name instead header.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.