0

I am trying to create a chrome extension that calls my rails app's api. currently the api returns json and it works fine, however when I try to build it into a chrome extension, it says :

Refused to load script from 'http://mysite.com/demo?q=hello?callback=jQuery16409466155741829425_1342489669670&_=1342489677171' because of Content-Security-Policy.

I looked up the document http://code.google.com/chrome/extensions/contentSecurityPolicy.html and it sounds like I can't do this unless I implement my site into a https version. (under "Relaxing the default policy" section) I am not sure if I understood correctly and it feels ridiculous to make such a big change just because of this. Am I misunderstood? Or is there a workaround to this? Thank you.

Vlad
  • 8,038
  • 14
  • 60
  • 92

2 Answers2

1

In a Chrome extension, cross-site XMLHttpRequests are allowed, provided that you define the source in the manifest file - see http://code.google.com/chrome/extensions/xhr.html.

A JSONP implementation loads an external script using the <script> tag, and inserts it in the document. Unless the source is whitelisted through the "content_security_policy" entry, JSONP cannot be used when manifest version 2 is active (do not use manifest v1 to overcome this, because it's deprecated, and a suitable alternative already exist).

When you're unable to receive a JSON response instead of JSONP, use an ordinary request to fetch the data, cut off the callback, then parse it. Eg:

// response is the response from the server
// Received through `XMLHttpRequest`, jQuery.ajax, or whatever you used
// cuts of jQuery....(  and the trailing )
response = response.replace(/^[^(]*\(/, '').replace(/\);?$/, '');
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • See also http://stackoverflow.com/questions/11842954/get-json-in-chrome-plugin/11845618#11845618 (especially if you're using jQuery) – Rob W Aug 14 '13 at 22:56
0

By default browsers do not allow this because of the same origin policy.

However you can get around this by making a jsonp request.

As you using jquery this super easy with getJSON method

jamjam
  • 3,171
  • 7
  • 34
  • 39
  • Sorry for the confusion, I think i need to clarify my question. I am already using jsonp and that's why it's working from a web page based call. However when I try to take it to chrome extension it doesn't work... – Vlad Jul 17 '12 at 02:42
  • Just becuase you are returning JSON, doesnt mean you are doing a JSON-P request. Post some code. – Andrew Hall Jul 17 '12 at 09:24