【问题标题】:Chrome Extension to Loop to Close Non-Selected TabsChrome 扩展以循环关闭未选择的标签
【发布时间】:2014-05-04 11:38:49
【问题描述】:

我为 Safari 制作了这个扩展,可以关闭当前页面上的非活动标签

 (var tabss = safari.application.activeBrowserWindow.tabs;

            for (n=0; n<tabss.length; n++) 
              {
          if(tabss[n] != safari.application.activeBrowserWindow.activeTab)

         tabss[n].close();
             }
    )

我想为 Chrome 做同样的事情。但是 Chrome 有不同的做事方式。我仍然想在选项卡的索引上运行循环,如果它们不是选定的选项卡,则关闭它们。我已经能够获得窗口索引的长度,但我不知道如何多次执行关闭选项卡循环,以确保不会关闭选定的选项卡。我已经能够通过这样做获得长度:

<html>
  <head>
    <script>
    var targetWindow = null;
    var tabCount = 0;

    function start(tab) {
      chrome.windows.getCurrent(getWindows);
    }

    function getWindows(win) {
      targetWindow = win;
      chrome.tabs.getAllInWindow(targetWindow.id, getTabs);
    }

    function getTabs(tabs) {
      tabCount = tabs.length;
      alert(tabCount);

    }

    // Set up a click handler so that we can merge all the windows.
    chrome.browserAction.onClicked.addListener(start);
    </script>
  </head>
</html>

http://code.google.com/chrome/extensions/samples.htmlMerge Windows 收集。

现在我想运行循环,但我不知道如何告诉循环不要关闭选定的选项卡。我正在考虑让循环将循环选项卡与所选窗口的选项卡 ID 进行比较,它不会关闭它并移动到循环中的下一个选项卡索引号。

类似:

(
            for (n=0; n<tabCount; n++) 
              {
          if(chrome.tabs[n].id != tab.id)

         chrome.tabs[n].remove();
             }
)

但我不知道如何注入当前的 tabid,因为所有回调函数都有这个 javascript hack/noob 难倒。据我了解,我无法从另一个函数中引入变量。

【问题讨论】:

    标签: google-chrome tabs


    【解决方案1】:

    应该这样做:

    // when a browser action is clicked, the callback is called with the current tab
    chrome.browserAction.onClicked.addListener(function(curtab)
    {
         // get the current window
        chrome.windows.getCurrent(function(win)
        {
            // get an array of the tabs in the window
            chrome.tabs.getAllInWindow(win.id, function(tabs)
            {
                for (i in tabs) // loop over the tabs
                {
                     // if the tab is not the selected one
                    if (tabs[i].id != curtab.id)
                    {
                        // close it
                        chrome.tabs.remove(tabs[i].id)
                    }
                }
            });
        });
    });
    

    【讨论】:

    • 哇。很快就把那些标签敲下来了。谢谢。昨晚我花了几个小时试图学习这些东西/弄明白。哈哈。谢谢。
    猜你喜欢
    • 2015-04-29
    • 1970-01-01
    • 2011-11-18
    • 2015-08-13
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    相关资源
    最近更新 更多