chrome extension read value problem
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 mig开发者_如何转开发ht be? Thanks.
Chrome API calls are asynchronous (think ajax calls), so they are not executed in order. You can't return
from such methods, you need to use callbacks.
function getOpenedTabs(callback) {
chrome.windows.getAll({populate: true}, function(wins) {
var openedTabs = [];
for (var w=0; w<wins.length;w++) {
for (var t=0;t<wins[w].tabs.length;t++) {
if (wins[w].tabs[t].id !== undefined) { //I don't think this check is needed
openedTabs.push(wins[w].tabs[t]);
}
}
}
if(callback) {
callback(openedTabs);
}
});
}
chrome.tabs.onCreated.addListener(function(tab){
getOpenedTabs(function(openedTabs) {
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");
}
});
});
You don't need to use getAllInWindow()
, you can get all tabs with getAll()
. Also using in
to iterate over an array isn't a good practice.
精彩评论