首页 > 解决方案 > 如何选择当前选项卡右侧的所有选项卡?

问题描述

如果您右键单击 Chrome 浏览器顶部的任何选项卡,您将在右侧看到一个名为“关闭选项卡”的选项。这将关闭当前活动选项卡右侧的所有选项卡。我正在尝试使用 Chrome 扩展程序做类似的事情。可以使用诸如“当前活动选项卡的索引直到最后一个选项卡的索引”之类的循环来选择右侧的选项卡吗?

以下是开源 Chrome 扩展程序的源代码。该函数选择当前窗口中除活动选项卡外的所有选项卡并“暂停”它们。我正在尝试编写一个类似的函数,但不是所有选项卡,它只需要选择活动选项卡右侧的选项卡。

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

标签: javascriptgoogle-chrome-extension

解决方案


每个选项卡都有一个index显示其位置的选项卡。例如,第 3 个选项卡的索引为 2(从 0 开始)。

tab.index +1因此,任何选项卡右侧的选项卡意味着tabs.length

例如...
将选项卡放在活动选项卡的右侧

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

获取活动选项卡左侧的选项卡

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

推荐阅读