Reputation: 493
I tried to assign a tab to a variable; but I failed. Here is my code:
var tab;
chrome.tabs.get(id, function(t) {
tab = t;
console.log("tab: " + tab); // here the printed result is right
});
console.log("(after assignment) tab: " + tab); // always get "undefined"
The code is simple but I don't know where the problem is...
Upvotes: 0
Views: 416
Reputation: 111325
The problem is in asynchronous Chrome API calls, meaning that you don't receive response from them immediately. You can rewrite your code in this way for example:
var tab;
chrome.tabs.get(id, function(t) {
tab = t;
console.log("tab: " + tab); // here the printed result is right
afterAssignment();
});
function afterAssignment() {
console.log("(after assignment) tab: " + tab); // always get "undefined"
//the rest of the code that needs to use tab var
}
Upvotes: 3