javascript - 在 Chrome 扩展中获取 JSON

标签 javascript ajax json google-chrome-extension content-security-policy

我的 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/

相关文章:

javascript - 如何在 Android 中突破 Twitter 应用内浏览器?

javascript - 为什么 element.setAttribute ('checked' , true) 不起作用?

javascript - 如何删除 html 5 表单元素的默认样式?

javascript - 将新属性添加到另一个具有不同长度的数组的对象数组中,因此一旦数组完成迭代,它将再次从第一个开始

javascript - 无法使用 AJAX 调用在后端服务器上保存上传视频的 blob URL

c# - Jquery ajax 调用以在 MVC 中传递 JSON 数组(500 内部服务器错误)

javascript - 如何将 JSON 文本转换为 JSON 对象?

javascript - 应用程序可以在浏览器上运行,但不能在设备上运行 CORS 问题?无网络事件

javascript - 在 Javascript 中使用通过 PHP 返回的 JSON

php - 安卓 JSON 不工作