9

Small problem with my chrome extension.

I just wanted to get a JSON array from another server. But manifest 2 doesn't allow me to do it. I tried specify content_security_policy, but the JSON array is stored on a server without SSL cert.

So, what should I do without using manifest 1?

Xan
  • 74,770
  • 16
  • 179
  • 206
user1175307
  • 151
  • 1
  • 1
  • 13
  • http://stackoverflow.com/questions/2258206/chrome-extension-ip-domain-permissions read this post, it will hopefully help you out –  Aug 07 '12 at 09:49
  • I don't get it. I have correct permissions in my manifest. But the problem is, that jQuery $.getJSON function can't work without content_security_policy settings. But content_security_policy accepts only HTTPS pages. – user1175307 Aug 07 '12 at 12:07

1 Answers1

15

The CSP cannot cause the problem you've described. It's very likely that you're using JSONP instead of plain JSON. JSONP does not work in Chrome, because JSONP works by inserting a <script> tag in the document, whose src attribute is set to the URL of the webservice. This is disallowed by the CSP.

Provided that you've set the correct permission in the manifest file (e.g. "permissions": ["http://domain/getjson*"], you will always be able to get and parse the JSON:

var xhr = new XMLHttpRequest();
xhr.onload = function() {
    var json = xhr.responseText;                         // Response
    json = json.replace(/^[^(]*\(([\S\s]+)\);?$/, '$1'); // Turn JSONP in JSON
    json = JSON.parse(json);                             // Parse JSON
    // ... enjoy your parsed json...
};
// Example:
data = 'Example: appended to the query string..';
xhr.open('GET', 'http://domain/getjson?data=' + encodeURIComponent(data));
xhr.send();

When using jQuery for ajax, make sure that JSONP is not requested by using jsonp: false:

$.ajax({url:'...',
        jsonp: false ... });

Or, when using $.getJSON:

$.getJSON('URL which does NOT contain callback=?', ...);
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Thanks a lot, man! I don't know what happened, but it works without callback=? like a charm! It didn't work in the past, but now it's OK :-) So solved! – user1175307 Aug 07 '12 at 22:09
  • The real first working exemple i found in the web on hours of search and try. If i Use: var json = this.response; i get it working. What is the difference than responseText ? – Gino Nov 20 '16 at 23:22