Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery.ajax in a Google Chrome extension

I use jquery.ajax function to post data from google chrome extension to my web service as code below:

$.ajax({
            type: "POST",
            url: serviceUrl,
            data: data,
            success: function(msg){
                if(typeof(Me.config.onSumitted) == "function"){
                    Me.config.onSumitted(msg);
                }
           },
           error: function(){
                if(typeof(Me.config.onError) == "function"){
                    Me.config.onError();
                }
           }
         });

but i get an error:

XMLHttpRequest cannot load http://todomain.com/Service.asp. Origin http://fromtabdomain.com is not allowed by Access-Control-Allow-Origin.

how can i resolve it?

like image 217
Minh Nguyen Avatar asked Jul 23 '11 14:07

Minh Nguyen


4 Answers

you need to add a permission to you manifest.js file

"permissions": [
    "http://www.yourwebsite.com/"
  ],
like image 102
Gev Avatar answered Sep 23 '22 14:09

Gev


its because same origin policy set crossDomain to true (ise jquery version 1.5 or higher)

$.ajax({
            type: "POST", //or GET
            url: serviceUrl,
            data: data,
            crossDomain:true,
            cache:false,
            async:false,
            success: function(msg){
                //do some thing
           },
           error: function(jxhr){
               alert(jxhr.responseText);
                //do some thing
           }
         });
like image 29
Rafay Avatar answered Sep 25 '22 14:09

Rafay


I use native ajax to solve this problem.you can do that with following steps.

ajax = function(options, callback) {
  var xhr;
  xhr = new XMLHttpRequest();
  xhr.open(options.type, options.url, options.async || true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      return callback(xhr.responseText);
    }
  };
  return xhr.send();
};
like image 24
huip Avatar answered Sep 25 '22 14:09

huip


As @ChristopheCVB pointed out http://code.google.com/chrome/extensions/xhr.html tells you what to do:

Please add a permissions section to your manifest.json:

{
  "name": "yourExtension",

  "permissions": [
    "http://fromtabdomain.com"
  ]
}
like image 42
MarioW Avatar answered Sep 26 '22 14:09

MarioW