开发者

Find out tab that sent the response in chrome extension

开发者 https://www.devze.com 2023-03-06 23:24 出处:网络
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 can

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

精彩评论

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