一種常見也比較實用的方式是用 xhr:
function getData(url,callback){
var httpRequest = new XMLHttpRequest();//創建對象
httpRequest.open('GET', url, true);
httpRequest.withCredentials = true;//設置為包含 cookie
httpRequest.send();
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState==4 && httpRequest.status==200){
var data = httpRequest.responseText;//獲取到json字符串,還需解析
callback(data);
}
};
}
傳入 url 調用上面的函數則可在回調函數中得到響應體(json)。
用這種方法的前提是你要知道目標 url。
另一種不那么常用,也不那么好用的方式是:
將下面這個函數放到background.js中。
function getResponse(){
var currentTab;
var version = "1.0";
chrome.tabs.query( //get current Tab
{
currentWindow: true,
active: true
},
function(tabArray) {
currentTab = tabArray[0];
chrome.debugger.attach({ //debug at current tab
tabId: currentTab.id
}, version, onAttach.bind(null, currentTab.id));
}
)
function onAttach(tabId) {
chrome.debugger.sendCommand({ //first enable the Network
tabId: tabId
}, "Network.enable");
chrome.debugger.onEvent.addListener(function(debuggeeId, message, params){
if (currentTab.id != debuggeeId.tabId) {
alert("currentTab.id != debuggeeId.tabId")
return;
}
if (message == "Network.responseReceived") {
chrome.debugger.sendCommand({
tabId: debuggeeId.tabId
}, "Network.getResponseBody", {
"requestId": params.requestId
}, function(response) {
console.log("****************")
console.log(JSON.stringify(response))
});
}
});
}
}
讓popup.js調用函數就可以將響應體打印到背景頁的控制台上:
參考:chrome-extension-how-to-get-http-response-body
這種方式最終會在瀏覽器上部彈出一個提示窗口,比較難看,似乎有能夠去除的方法,但沒有深究,想去除可以的話可以查看 Chrome 擴展開發者文檔中的 devtool API,里面應該提供了關閉提示的方法。