在 Chrome 扩展程序中获取 JSON

IT技术 javascript ajax json google-chrome-extension content-security-policy
2021-02-28 04:46:39

我的 chrome 扩展程序的小问题。

我只是想从另一台服务器获取一个 JSON 数组。但是清单 2 不允许我这样做。我尝试指定content_security_policy,但 JSON 数组存储在没有 SSL 证书的服务器上。

那么,如果不使用清单 1,我该怎么办?

1个回答

CSP不能引起你所描述的问题。您很可能使用的是 JSONP 而不是普通的 JSON。JSONP 在 Chrome 中不起作用,因为 JSONP 通过<script>在文档中插入一个标签来工作,该标签的src属性设置为 web 服务的 URL。这是 CSP 不允许的

假设您已在清单文件中设置了正确的权限(例如"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=?', ...);
我在网上经过数小时的搜索和尝试找到了真正的第一个工作示例。如果我使用:var json = this.response; 我得到它的工作。与 responseText 有什么区别?
2021-04-29 04:46:39
非常感谢,伙计!我不知道发生了什么,但它在没有 callback=? 就像一个魅力!它过去不起作用,但现在可以了:-) 解决了!
2021-05-16 04:46:39