Minh Nguyen
Minh Nguyen

Reputation: 2039

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?

Upvotes: 11

Views: 35041

Answers (5)

Gev
Gev

Reputation: 149

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

"permissions": [
    "http://www.yourwebsite.com/"
  ],

Upvotes: 14

huip
huip

Reputation: 51

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();
};

Upvotes: 1

MarioW
MarioW

Reputation: 86

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"
  ]
}

Upvotes: 3

Rafay
Rafay

Reputation: 31043

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
           }
         });

Upvotes: 1

ChristopheCVB
ChristopheCVB

Reputation: 7305

You can have a look at this page to achieve what you want :

http://code.google.com/chrome/extensions/xhr.html

It is just about setting permissions...

Upvotes: 13

Related Questions