javascript - Chrome扩展程序: runtime.运行tabs.get/tabs.remove时出现lastError:没有id为0的选项卡

标签 javascript google-chrome google-chrome-extension tabs

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

我总是收到这些错误:

Unchecked runtime.lastError while running tabs.get: No tab with id:0
Unchecked runtime.lastError while running tabs.remove: No tab with 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 的选项卡,因为我使用了事件选项卡的 TabId(使用 getTabId),不是吗?

如何获取当前选项卡的正确Id,或者是否有其他方法将当前窗口的所有选项卡存储在数组中,然后关闭所有选项卡?

我希望有人能帮助我;)

最佳答案

Xan 为您提供了有关正在发生的事情的极好线索,但让我尝试回答您的问题,因为它特别与 Chrome 扩展相关。 getTabID 中的回调函数异步运行,这意味着它不会阻止任何其他可能运行的代码。因此,在 closeBundle 中,您调用 getTabID,它开始运行,但 closeBundle 甚至在 getTabID 完成其回调运行之前继续运行。因此,当您调用 chrome.tabs.get 时,tabID 仍然为 0,并且会出现错误。简而言之,由于 JavaScript 的异步特性,您的代码的整个架构将无法工作。

一种现成的解决方案是将所有内容包装在回调函数中(通常称为回调 hell )。我已经构建了带有 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
        }
      });
  });
}

此代码未经测试或旨在运行,只是为了让您了解嵌套回调的含义。希望这有帮助,祝你好运。

关于javascript - Chrome扩展程序: runtime.运行tabs.get/tabs.remove时出现lastError:没有id为0的选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29130394/

相关文章:

javascript - Chrome 扩展程序太慢

javascript - 从对象数组中删除除最后一个相似键之外的所有键

javascript - 将值从 RouterStateSnapshot 传递到 Angular 2 应用程序中的根路由文件

php - 一页上有很多图像,有些无法加载

google-chrome - 从命令行读取 Chrome cookie

android - 在 manifest.json 中添加了图标,但在启动画面中没有图标

javascript - 使用 Chrome 存储切换值

javascript - Regex.test() 给出真假顺序?

javascript - Chrome 扩展程序 : Is it possible to create a TCP/Websocket based server on a folder?

javascript - Chrome 扩展程序 : console. 日志检测器