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?
1 Answer
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!
1 Comment
jeffbRTC
Devin,
header is undefined in code. it should be resp.responseHeaders[len].name instead header.
--disable-web-securityChrome flag. If the request is generated by your extension, you need to add the URL to thepermissionssection of your manifest file.