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