Get JSON in a Chrome extension

江枫思渺然 提交于 2019-12-17 07:31:20

问题


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?


回答1:


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=?', ...);


来源:https://stackoverflow.com/questions/11842954/get-json-in-a-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!