Nguyen  Minh Binh Nguyen Minh Binh - 1 year ago 97
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": [

And here is the jQuery code to invoke outside sites:

var host = "";
var xhr = new XMLHttpRequest();"GET", host, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status === 200) {
} else {
alert("Error with status:" + xhr.status);

Above code work correctly with https sites, eg:
, ... but not working with http site such as:

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download