Is it possible to use CORS when writing a google chrome extension?
I saw this, http://developer.chrome.com/extensions/contentSecurityPolicy.html
And I tried
To enable cross-origin Ajax from your extension to Twitter, you simply need to list Twitter as a host permission in your manifest:
...
"permissions": [
"*://*.twitter.com/*"
],
...
As of Chrome 73, cross site requests are blocked. (Even if you have the hosts in your permissions property.) Some sites seem to get through unblocked but I'm sure eventually most won't.
You have to make the request in a background page...
Add a section to your manifest.json
to point to the background page.
"background": {
"scripts": ["bg_page.js"],
"persistent": false
}
Create the background page: bg_page.js
chrome.runtime.onMessage.addListener(
function(url, sender, onSuccess) {
fetch(url)
.then(response => response.text())
.then(responseText => onSuccess(responseText))
return true; // Will respond asynchronously.
}
);
Then use it in main.js
chrome.runtime.sendMessage( //goes to bg_page.js
url,
data => dataProcessFunction(data)
);
If you do anything like console.log()
from the bg page, click the "inspect views background page" link in your extension's square in chrome's extensions manager and you'll get a separate dev tools window for everything that happens with your background page.
If you want to see the docs for yourself, check out step 2 of the Recommended Developer Actions section here: https://www.chromium.org/Home/chromium-security/extension-content-script-fetches#TOC-2.-Avoid-Cross-Origin-Fetches-in-Content-Scripts
Add the header Access-Control-Allow-Origin: * to the response of your remote server if possible. Here is a tutorial for various backend servers: add CORS support to backend server