Chrome 扩展程序:选择下一个标签?

Him*_*u P 5 tabs google-chrome-extension

Chrome 扩展程序:如何激活当前选项卡旁边的选项卡(即右侧的选项卡)。这是我拥有的代码,但它无法正常工作 - 而不是下一个选项卡,一个随机选项似乎被激活。

特别是我认为选项卡的索引属性在当前页面中从左到右指示其索引是否正确?

// switch to next tab
function nextTab() {
  // first, get currently active tab
  chrome.tabs.query({active: true}, function(tabs) {
    if (tabs.length) {
      var activeTab = tabs[0],
      tabId = activeTab.id,
      currentIndex = activeTab.index;
      // next, get number of tabs in the window, in order to allow cyclic next
      chrome.tabs.query({currentWindow: true}, function (tabs) {
        var numTabs = tabs.length;
        // finally, get the index of the tab to activate and activate it
        chrome.tabs.query({index: (currentIndex+1) % numTabs}, function(tabs){
          if (tabs.length) {
            var tabToActivate = tabs[0],
            tabToActivate_Id = tabToActivate.id;
            chrome.tabs.update(tabToActivate_Id, {active: true});
          }
        });
      });
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

编辑:

问题似乎是查询chrome.tabs.query({active: true}, function(tabs){...})似乎返回了多个选项卡。我的窗口目前有 14 个选项卡,其中 7 个似乎具有activetrue 属性。这里发生了什么?我也尝试过基于 查询{selected: true},但给出了错误:Invalid value for argument 1. Property 'selected': Unexpected property.

任何帮助将非常感激

Dan*_*Lee 4

您似乎打开了多个 Chrome 实例。
要将选项卡查询的上下文保留到当前实例,您应该添加currentWindow: true到您所做的每个查询中。否则,它会搞乱所有其他实例的所有选项卡 ID。

例如,您的第一个查询将如下所示:

chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) { // ...
Run Code Online (Sandbox Code Playgroud)