Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension: select next tab?

Chrome extension: How can I activate the tab next to the current one (i.e. the one to its right). This is the code I have, but it doesn't work correctly - instead of the next tab, a random one seems to get activated.

In particular am I right to assume that a tab's index property indicates its index from left to right in the current page?

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

EDIT:

The issue seems to be that the query chrome.tabs.query({active: true}, function(tabs){...}) seems to be returning more than one tab. My window currently has 14 tabs, and 7 of them seem to have the active property true. What's going on here? I also tried querying based on {selected: true}, but gives the error: Invalid value for argument 1. Property 'selected': Unexpected property.

Any help would be much appreciated

like image 925
Himanshu P Avatar asked Oct 05 '22 06:10

Himanshu P


1 Answers

It seems like you have multiple instances of Chrome opened.
To keep the context of the tab queries to your current instance you should add currentWindow: true to every query you make. Otherwise it will screw up with all tab ids from all other instances.

So as example your first query would look like:

chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) { // ...
like image 138
dan-lee Avatar answered Oct 13 '22 09:10

dan-lee