I’m building my chrome extension and I’ve got weird problem. This is script I’m running in background page:
function getOpenedTabs() {
var openedTabs = [];
chrome.windows.getAll({}, function(wins) {
for (var w in wins) {
if (wins[w].id !== undefined) {
chrome.tabs.getAllInWindow(wins[w].id, function(tabs) {
for (var t in tabs) {
if (tabs[t].id !== undefined) {
openedTabs.push(tabs[t]);
}
}
});
}
}
});
return openedTabs;
}
chrome.tabs.onCreated.addListener(function(tab){
var openedTabs = getOpenedTabs();
var length = openedTabs.length;
console.log("Quantity of tabs: " + length );
if (length > 20) {
openedTabs.sort(function(a,b){return a.visitCount - b.visitCount});
var t = openedTabs.shift();
chrome.tabs.remove(t.id);
console.log("The extension closed the " + t.title + " tab");
}
});
In debugging mode openedTabs.length returns correct value. But when I removed all breakpoints then openedTabs.length returns zero all time.
What kind of problem it might be?
Thanks.
Chrome API calls are asynchronous (think ajax calls), so they are not executed in order. You can’t
returnfrom such methods, you need to use callbacks.You don’t need to use
getAllInWindow(), you can get all tabs withgetAll(). Also usinginto iterate over an array isn’t a good practice.