How to select all tabs to the right of current tab?

Viewed 818

If you right click on any tab at the top of Chrome browser, you will see an option called Close tabs to the right. This closes all tabs to the right of the current active tab. I'm trying to do something similar with a Chrome extension. Can the tabs to the right be selected using a loop like "for index of current active tab until index of last tab?"

Following is the source code of an open source Chrome extension. The function selects all tabs in the current window except for the active tab and "suspends" them. I am trying to write a similar function but instead of all tabs, it needs to select only the tabs to the right of the active tab.

  function suspendAllTabs(force) {
    const forceLevel = force ? 1 : 2;
    getCurrentlyActiveTab(activeTab => {
      if (!activeTab) {
        gsUtils.warning(
          'background',
          'Could not determine currently active window.'
        );
        return;
      }
      chrome.windows.get(activeTab.windowId, { populate: true }, curWindow => {
        for (const tab of curWindow.tabs) {
          if (!tab.active) {
            gsTabSuspendManager.queueTabForSuspension(tab, forceLevel);
          }
        }
      });
    });
2 Answers

Each tab has an index which shows its position. For example, the 3rd tab will have an index of 2 (starts from 0).

Therefore, tab to the right of the any tab means tab.index +1 to tabs.length

For example ...
Getting the tabs to the right of the active tab

// get all the tabs in current window
chrome.tabs.query({currentWindow: true}, tabs => {

  let activeIndex;
  for (const tab of tabs) {
    // set the activeIndex so we wont have to run a loop on the tabs twice
    if (tab.active) { activeIndex = tab.index; }

    // tabs to the right of the active tab will have higher index
    if(typeof activeIndex !== 'undefined' && tab.index > activeIndex) {

      // tabs is on the right of the active tab ... do whatever needed
    }
  }
});

Getting the tabs to the left of the active tab

// get all the tabs in current window
chrome.tabs.query({currentWindow: true}, tabs => {

  for (const tab of tabs) {
    // stop when reached the active tab
    if (tab.active) { break; }

    // tabs to the left of the active tab ... do whatever needed
  }
});

Another option which can be useful in many situations and is very intuitive is to use filtering to get your new tabs.

Adding to @erosman’s answer. When you get the tabs you can:

// All to right of current
tabs = tabs.filter((x)=> x.index > activeTab.index);

// All to left of current 
tabs = tabs.filter((x)=> x.index < activeTab.index);

// Do whatever with the new tabs.

Similar approach can be taken to get any tab as long as the condition in the filter is met!

Related