我试图找到解决方案,但我发现的唯一一件事就是随机TabId不存在。但这并没有解决我的问题:
我总是收到这些错误:
运行tabs.get时未经检查的runtime.lastError:没有标识为:0的标签 运行tabs.remove时未经检查的runtime.lastError:没有id为0的选项卡
我的代码:
var tabnumber = 0; //the number of tabs in the current window
var tabID = 0; //id of the active tab
function closeBundle(){
getTabnumber();
for(i=0;i<tabnumber;i++){
getTabID();
chrome.tabs.get(tabID , function(tab){ //here is the first problem
insert[i] = tab; //for saving all Tabs in an array
});
chrome.tabs.remove(tabID); //here the second one
}
chache[active] = insert; //I save the insert array in another array
}
function getTabnumber(){
chrome.tabs.query({'currentWindow': true}, function(tabarray){
tabnumber = tabarray.length;
});
}
function getTabID(){
chrome.tabs.query({'currentWindow': true, 'active': true}, function(tabArray){
tabID = tabArray[0].id;
});
}
我不知道为什么没有具有此特定ID的Tab,因为我使用了活动Tab的TabId(使用getTabId),不是我?
如何获取当前标签的正确ID或是否有另一种方法将当前窗口的所有标签存储在一个数组中,然后关闭所有标签?
我希望有人可以帮助我;)
答案 0 :(得分:1)
Xan给了你一个很好的线索,但是让我试着回答你的问题,因为它特别与chrome扩展有关。 getTabID中的回调函数以异步方式运行,这意味着它不会阻止其他任何代码运行。因此,在closeBundle中,您调用getTabID,它开始运行,但即使在getTabID完成运行其回调之前,closeBundle仍继续运行。因此,当您调用chrome.tabs.get时,tabID仍为0,并且您收到错误。简而言之,由于JavaScript的异步特性,代码的整个架构将无法工作。
一个现成的解决方案是将所有内容包装在回调函数中(通常称为回调地狱)。我已经构建了带有5或6个嵌套回调函数的chrome扩展。人们真的需要了解这种异步行为来编程和调试chrome扩展以及JavaScript。快速谷歌搜索将为您提供有关该主题的无尽文章。 Xan的评论是一个很好的起点。
但是例如在你的代码中,一些伪代码可能看起来像这样:
function getTabnumber(){
chrome.tabs.query({'currentWindow': true}, function(tabarray){
tabnumber = tabarray.length;
for(i=0;i<tabnumber;i++){
chrome.tabs.query({'currentWindow': true, 'active': true}, function(tabArray){
tabID = tabArray[0].id;
chrome.tabs.get(tabID , function(tab){ //here is the first problem
insert[i] = tab; //for saving all Tabs in an array
});
chrome.tabs.remove(tabID); //here the second one
}
});
});
}
此代码未经过测试或打算运行,只是为了让您了解嵌套回调的含义。希望这有帮助,祝你好运。