开发者

Find out tab that sent the response in chrome extension

In the background script, I send requests to each tab. My question is how do I get the tab from which the response came from in the callback function? Since sendRequest is asynchronous, the tab.id cannot be used in the callbock.

for (var i = 0, tab; tab = tabs[i]; i++) {
    chrome.tabs.sendRequest(tab.id, {play:0}, function(respo开发者_运维知识库nse) {
        // do something here
        // how do i get the tab.id from which the response come from?
    });
}


You need to create closure:

for (var i = 0, tab; tab = tabs[i]; i++) {
    chrome.tabs.sendRequest(tab.id, {play:0}, (function(tabId) { 
        return function(response) {
            //tabId stores current tab id
            console.log("response from:", tabId);
        }
    })(tab.id));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜