5

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

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

// 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});
          }
        });
      });
    }
  });
}

编辑:

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

任何帮助将非常感激

4

1 回答 1

4

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

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

chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) { // ...
于 2013-04-29T12:48:26.570 回答