在Chrome扩展中使用jQuery.getJSON [英] Using jQuery.getJSON in Chrome Extension

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

问题描述

我需要在Chrome扩展程序中执行跨域请求。我知道我可以通过消息传递,但我宁愿坚持只使用jQuery成语(所以我的javascript也可以作为< script src => )。



I做正常的:

  $。getJSON(http://api.flickr.com/services/feeds/photos_public.gne ?tags = cat& tagmode = any& format = json& jsoncallback =?,function(data){
console.log(data);
});

但是在错误控制台中我看到:

 未捕获的ReferenceError:未定义jsonp1271044791817 

jQuery不是将回调函数正确插入文档中?我能做些什么来完成这项工作?



(如果我把代码粘贴到一个chrome控制台中,它可以正常工作,但是如果我把它作为page.js )

解决方案

唉,这些都不起作用,所以我最终通过background.html。

background.html

 < script src = http://code.jquery.com/jquery-1.4.2.js >< /脚本> 
< script>
函数onRequest(request,sender,callback){
if(request.action =='getJSON'){
$ .getJSON(request.url,callback);
}
}

chrome.extension.onRequest.addListener(onRequest);
< / script>

javascripts / page.js

  chrome_getJSON = function(url,callback){
console.log(sending RPC);
chrome.extension.sendRequest({action:'getJSON',url:url},callback);


$(function(){
//使用chrome_getJSON而不是$ .getJSON
});


I need to do a cross-domain request in a chrome extension. I know I can it via message passing but I'd rather stick to just jQuery idioms (so my javascript can also work as a <script src="">).

I do the normal:

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(data) {
  console.log(data);
});

but in the error console I see:

Uncaught ReferenceError: jsonp1271044791817 is not defined

Is jQuery not inserting the callback function correctly into the document? What can I do to make this work?

(If I paste the code into a chrome console, it works fine, but if I put it as the page.js in an extension is when the problem appears.)

解决方案

Alas, none of these worked, so I ended up doing the communication via the background.html.

background.html

<script src="http://code.jquery.com/jquery-1.4.2.js"></script>
<script>
function onRequest(request, sender, callback) {
  if (request.action == 'getJSON') {
    $.getJSON(request.url, callback);
  }
}

chrome.extension.onRequest.addListener(onRequest);
</script>

javascripts/page.js

chrome_getJSON = function(url, callback) {
  console.log("sending RPC");
  chrome.extension.sendRequest({action:'getJSON',url:url}, callback);
}

$(function(){
  // use chrome_getJSON instead of $.getJSON
});

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

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