Javascript Chrome扩展名:runtime.lastError运行tabs.get/tabs.remove:没有id为0的选项卡

Javascript Chrome扩展名:runtime.lastError运行tabs.get/tabs.remove:没有id为0的选项卡,javascript,google-chrome,google-chrome-extension,tabs,Javascript,Google Chrome,Google Chrome Extension,Tabs,我试图找到一个解决方案,但我唯一发现的是如果随机TabId不存在。但这并不能解决我的问题: 我总是会遇到这些错误: 运行选项卡时未选中runtime.lastError。获取:没有id为0的选项卡 未选中runtime.lastError,运行选项卡时出错。删除:没有id为0的选项卡 我的代码: var tabnumber = 0; //the number of tabs in the current window var tabID = 0; //id of the active tab

我试图找到一个解决方案,但我唯一发现的是如果随机TabId不存在。但这并不能解决我的问题:

我总是会遇到这些错误:

运行选项卡时未选中runtime.lastError。获取:没有id为0的选项卡
未选中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;
  });
}
var tabnumber=0//当前窗口中的选项卡数
var-tabID=0//活动选项卡的id
函数closeBundle(){
getTabnumber();

对于(i=0;iXan为您提供了一个很好的线索,让我试着回答您的问题,因为它特别与chrome扩展相关。getTabID中的回调函数异步运行,这意味着它不会阻止任何其他代码的运行。因此,在closeBundle中,您调用getTabID,它开始运行,但closeBundle co在getTabID完成其回调运行之前继续运行。因此,当您调用chrome.tabs.get时,tabID仍然为0,并且您会收到一个错误。简而言之,由于JavaScript的异步性质,您的代码的整个体系结构将无法工作

一个现成的解决方案是将所有内容包装在回调函数中(通常称为回调地狱)。我构建了带有5或6个嵌套回调函数的chrome扩展。编写和调试chrome扩展和JavaScript时,人们确实需要了解这种异步行为。快速的Google搜索将为您提供关于该主题的无休止的文章。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
        }
      });
  });
}
函数getTabnumber(){ chrome.tabs.query({'currentWindow':true},函数(tabarray){ tabnumber=tabarray.length;
对于(i=0;i)另一个好问题是,我通常用Java开发,并且从几周前开始学习Javascript。我不知道我必须用不同于Java的Javascript进行开发。但现在代码工作正常。谢谢,您设置
tabID=0
,然后设置
chrome.tabs.get(tabID
?显然这将是一个错误,因为没有Id为零的选项卡!您可以通过向
chrome.tabs.get
添加回调来读取lastError,例如:
chrome.tabs.get(tabID,函数(tab){let e=chrome.runtime.lastError;});
。请参阅