Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

javascript - Get JSON in a Chrome extension

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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(/^[^(]*(([Ss]+));?$/, '$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=?', ...);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...