chrome拓展 跨站,chrome扩展程序中无法跨站点ajax api调用吗?

解决Chrome扩展跨域问题
本文探讨了在使用Chrome扩展程序调用外部API时遇到的跨域问题,并提供了几种解决方案,包括通过修改manifest文件允许跨域请求及如何处理JSONP响应。

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 :

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

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.

解决方案

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.

A JSONP implementation loads an external script using the 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).

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(/\);?$/, '');

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值