2013-04-29 49 views
2

Chrome擴展程序:我如何激活當前選項卡旁邊的選項卡(即右邊的那個選項卡)。這是我的代碼,但它不能正常工作 - 而不是下一個標籤,隨機的一個似乎被激活。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}); 
      } 
     }); 
     }); 
    } 
    }); 
} 

編輯:

這個問題似乎是在查詢chrome.tabs.query({active: true}, function(tabs){...})似乎返回多個選項卡。 我的窗口當前有14個選項卡,其中7個似乎具有active屬性。這裏發生了什麼?我也試過基於{selected: true}查詢,但提供了錯誤:Invalid value for argument 1. Property 'selected': Unexpected property.

任何幫助,將不勝感激

+0

此代碼對我的作品 – 2013-04-29 10:37:14

+0

感謝您試用一下。編輯帖子以更新。 – 2013-04-29 10:55:19

+1

你打開了多個實例嗎?如果是這樣的話,嘗試在你的第一個查詢對象中加入'currentWindow:true':'chrome.tabs.query({active:true,currentWindow:true}' – 2013-04-29 11:29:35

回答

3

好像你已經打開Chrome瀏覽器的多個實例。
要將標籤查詢的上下文保留到當前實例中,您應該爲每個查詢添加currentWindow: true。否則,它會與所有其他實例的所有標籤ID搞砸。

因此,作爲例如第一個查詢看起來像:

chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) { // ...