获取JSON在Chrome扩展 [英] Get JSON in a Chrome extension

查看:586
本文介绍了获取JSON在Chrome扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

小问题,我的浏览器扩展程序。

Small problem with my chrome extension.

我只是想获得来自其他服务器的JSON数组。但清单2不允许我这样做。我试图指定 content_security_policy ,但JSON数组存储没有SSL证书的服务器上。

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.

那么,我该怎么做,而不使用清单1?

So, what should I do without using manifest 1?

推荐答案

CSP 不会引起你所描述的问题。这很可能是你正在使用的不是纯JSON JSONP。 JSONP不能在Chrome工作,因为JSONP的工作原理是把<脚本> 在文档中标记,其的src 属性设置为web服务的URL。 这是通过在CSP 的禁止。

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.

只要你设置清单文件中的正确权限(如权限:HTTP://域名/的getJSON *] ,你会总是能够得到和解析JSON:

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();

当使用jQuery的阿贾克斯,确保JSONP没有使用要求 JSONP:假

When using jQuery for ajax, make sure that JSONP is not requested by using jsonp: false:

$.ajax({url:'...',
        jsonp: false ... });

或者,使用 $。的getJSON当 < /一>:

$.getJSON('URL which does NOT contain callback=?', ...);

这篇关于获取JSON在Chrome扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆