在Chrome扩展程序中无法跨站点Ajax api调用吗? [英] Impossible to cross site ajax api calls in a chrome extension?

查看:96
本文介绍了在Chrome扩展程序中无法跨站点Ajax api调用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个Chrome扩展程序,该扩展程序调用Rails应用程序的api.当前api返回json并且可以正常工作,但是当我尝试将其构建为chrome扩展程序时,它说:

I am trying to create a chrome extension that calls my rails app's api. currently the api returns json and it works fine, however when I try to build it into a chrome extension, it says :

由于内容安全政策,拒绝从"http://mysite.com/demo?q=hello?callback=jQuery16409466155741829425_1342489669670&_=1342489677171"加载脚本.

Refused to load script from 'http://mysite.com/demo?q=hello?callback=jQuery16409466155741829425_1342489669670&_=1342489677171' because of Content-Security-Policy.

我在 http://code.google.com/chrome/extensions中查找了文档/contentSecurityPolicy.html ,除非我将网站实现为https版本,否则听起来我无法做到这一点. (在放松默认策略"部分下)我不确定我是否理解正确,仅由于此原因做出如此大的更改感觉很可笑.我被误解了吗?还是有解决方法?谢谢.

I looked up the document http://code.google.com/chrome/extensions/contentSecurityPolicy.html and it sounds like I can't do this unless I implement my site into a https version. (under "Relaxing the default policy" section) I am not sure if I understood correctly and it feels ridiculous to make such a big change just because of this. Am I misunderstood? Or is there a workaround to this? Thank you.

推荐答案

在Chrome扩展程序中,允许跨站点XMLHttpRequest,前提是您在清单文件中定义了源-请参见 http://code.google.com/chrome/extensions/xhr.html .

In a Chrome extension, cross-site XMLHttpRequests are allowed, provided that you define the source in the manifest file - see http://code.google.com/chrome/extensions/xhr.html.

JSONP实现使用<script>标记加载外部脚本,并将其插入文档中.除非通过 "content_security_policy" 条目JSONP将源列入白名单清单版本 2处于活动状态时,不能使用该按钮(请勿 strong>使用清单v1来解决此问题,因为它已被弃用,并且已经存在合适的替代方案.

A JSONP implementation loads an external script using the <script> tag, and inserts it in the document. Unless the source is whitelisted through the "content_security_policy" entry, JSONP cannot be used when manifest version 2 is active (do not use manifest v1 to overcome this, because it's deprecated, and a suitable alternative already exist).

当您无法接收JSON响应而不是JSONP时,请使用普通请求来获取数据,切断回调,然后对其进行解析.例如:

When you're unable to receive a JSON response instead of JSONP, use an ordinary request to fetch the data, cut off the callback, then parse it. Eg:

// response is the response from the server
// Received through `XMLHttpRequest`, jQuery.ajax, or whatever you used
// cuts of jQuery....(  and the trailing )
response = response.replace(/^[^(]*\(/, '').replace(/\);?$/, '');

这篇关于在Chrome扩展程序中无法跨站点Ajax api调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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