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));
}
精彩评论