我的 chrome 扩展的小问题。
我只是想从另一台服务器获取一个 JSON 数组。但是 list 2 不允许我这样做。我尝试指定 content_security_policy
,但 JSON 数组存储在没有 SSL 证书的服务器上。
那么,不使用 manifest 1 怎么办呢?
最佳答案
CSP不会导致您描述的问题。您很可能使用的是 JSONP 而不是纯 JSON。 JSONP 在 Chrome 中不起作用,因为 JSONP 通过插入 <script>
来工作。文档中的标记,其 src
属性设置为 web 服务的 URL。 This is disallowed by the CSP .
如果您在 list 文件中设置了正确的权限(例如 "permissions": ["http://domain/getjson*"]
,您将始终能够获取和解析 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();
将 jQuery 用于 ajax 时,请确保不使用 jsonp: false
请求 JSONP :
$.ajax({url:'...',
jsonp: false ... });
或者,当使用 $.getJSON
时:
$.getJSON('URL which does NOT contain callback=?', ...);
关于javascript - 在 Chrome 扩展中获取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11842954/