Chrome扩展程序循环以关闭未选中的标签

时间:2010-12-08 19:53:26

标签: google-chrome tabs

我为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有不同的做事方式。我仍然希望在选项卡索引上运行循环,如果它们不是选定的选项卡则关闭它们。我已经能够获得windows索引的长度,但我不知道如何进行多次关闭选项卡循环,以确保不关闭所选选项卡。通过这样做我已经能够得到这个长度:

<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.html合并Windows收集。

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

类似的东西:

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

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

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

1 个答案:

答案 0 :(得分: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)
                }
            }
        });
    });
});
相关问题