extraeee
extraeee

Reputation: 3186

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(response) {
        // do something here
        // how do i get the tab.id from which the response come from?
    });
}

Upvotes: 2

Views: 117

Answers (1)

serg
serg

Reputation: 111265

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));
}

Upvotes: 3

Related Questions