Nguyen  Minh Binh Nguyen Minh Binh - 4 months ago 11
jQuery Question

Cross Domain API in Chrome Extensions

I am developing an extension for Google Chrome, which need to call some REST Api outside. My problem is I can't invoke API with http protocol while I can with https.
Here is my permission configuration:

"permissions": [
"tabs",
"storage",
"cookies",
"http://*/*",
"https://*/*"
]


And here is the jQuery code to invoke outside sites:

var host = "https://www.google.com.vn/";
var xhr = new XMLHttpRequest();
xhr.open("GET", host, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status === 200) {
alert(xhr.responseText)
} else {
alert("Error with status:" + xhr.status);
}
}
}
xhr.send();


Above code work correctly with https sites, eg:
https://www.google.com.vn/
,
https://www.linkedin.com/
, ... but not working with http site such as:
http://stackoverflow.com/


I am Android/iOS developer and I am really new with Chrome Extensions as well as jQuery. Please help to point me my mistake. Thanks in advance.

Answer

If you make Ajax call in content scripts, it will be restricted by the Content-Security-Policy header of the web page, which you couldn't (In fact shouldn't since you could remove that header via chrome.webRequest api, however that's bad and would put the site insecure) control.

One ideal suggestion would be moving the logic of sending ajax call to Background (event) page, which lives in the extension context and as long as you declared corresponding host permissions, you could feel free to use it. See Cross-Origin XMLHttpRequest for a detailed reference.