【问题标题】:How to select all tabs to the right of current tab?如何选择当前选项卡右侧的所有选项卡?
【发布时间】:2018-11-15 05:46:52
【问题描述】:

如果您右键单击 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);
          }
        }
      });
    });

【问题讨论】:

    标签: javascript google-chrome-extension


    【解决方案1】:

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

    因此,任何选项卡右侧的选项卡表示tab.index +1tabs.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
      }
    });
    

    【讨论】:

    • 非常感谢。我能够左右实现它。对于左边,我必须运行循环两次。
    • @NoobCoder 无需运行循环两次。事实上,左侧的选项卡更简单。我更新了答案以包括左侧的标签。
    • @erosman 是否有简单过滤不起作用的原因?你有你的选项卡对象数组,所以根据与当前选项卡索引的比较进行过滤以获取你需要的对象。似乎更直观,更易于实现。
    • @lbragile 这也有效。不同之处在于,如果您必须对每个选项卡执行某些操作,则过滤器将需要循环创建另一个过滤后的数组,然后在数组上运行任何函数,这意味着循环两次。这样你只循环一次。
    • @erosman 是有道理的。在我的情况下,进行过滤更有意义,但我看到你的方法在哪里也有用。谢谢你的解释。
    【解决方案2】:

    另一个在许多情况下都很有用且非常直观的选项是使用过滤来获取新标签。

    添加到@erosman 的答案。获得标签后,您可以:

    // 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.
    

    只要满足过滤器中的条件,就可以采取类似的方法来获取任何选项卡!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-24
      • 1970-01-01
      • 2014-01-31
      • 1970-01-01
      • 1970-01-01
      • 2019-10-08
      • 1970-01-01
      • 2011-05-14
      相关资源
      最近更新 更多