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 inserting this into the manifest, "content_security_policy": "script-src 'self' https://twitter.com/; object-src 'self'",
but an ajax requestion fails with XMLHttpRequest cannot load https://twitter.com/. Origin chrome-extension://olimhkjfpndfhdopbneamnekfalckinc is not allowed by Access-Control-Allow-Origin.
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/*"
],
...
Update 2025-03-03: Well Chrome got updated this morning to only allow v3 and all my favorite extensions are dead now, including my ad blocker. So I'm moving on... I'm just going to use a different (chromium-based) browser, but thanks for the upvotes.
Update 2024-07-03: This all applies to "manifest_version": 2
and even though Google has been threatening for a while to reject it, I'm still using it. Mainly because v3 doesn't have .getPackageDirectoryEntry()
which means I can't listen to my files and have hot reload. So I'm hoping they'll add that back in (or something similar) before I have to switch.
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.
If you're using manifest v3, you'll need a service_worker
property here intead of scripts
.
"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) //your callback
);
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With