2012-07-16 160 views
2

我想知道Google Chrome扩展程序是否可以发出HTTP请求并解析结果的正文(如Curl)。例如,有一个服务器1.2.3.4通过总结URL参数来回答问题?a=1&b=2。查询"http://1.2.3.4?a=1&b=2"将返回一个包含3的正文,并且我的扩展需要提交这样的查询并解析结果。Google Chrome扩展程序Http请求

任何帮助,将不胜感激。

+0

http://stackoverflow.com/questions/10769924/how-can-chrome-extensions-basically-curl-other-pages完全重复,但答案在那个版本上是非常不理想的 - 一个是没有答案的,另一个不适当地用jQuery编写。 – apsillers 2012-07-16 19:32:48

回答

13

是的,使用Cross-Origin XMLHttpRequest。设置权限,在清单中,并使用它像

var xhr = new XMLHttpRequest(); 
xhr.open("GET", "http://api.example.com/data.json", true); 
xhr.onreadystatechange = function() { 
    if (xhr.readyState == 4) { 
    // WARNING! Might be injecting a malicious script! 
    document.getElementById("resp").innerHTML = xhr.responseText; 
    ... 
    } 
} 
xhr.send(); 
+0

**谢谢,你帮了我很多!** – Eugene 2012-07-17 09:46:12