2015-06-24 113 views
3

我知道,当我输入mozrepl会话时,我处于一个特定浏览器窗口的上下文中。 在该窗口中,我可以做mozrepl:循环浏览所有窗口中的所有标签页Firefox浏览器

var tabContainer = window.getBrowser().tabContainer; 
var tabs = tabContainer.childNodes; 

,这将给我在那个窗口标签的数组。 我需要在所有打开的Firefox窗口中获取所有选项卡的数组,我该怎么做?

回答

4

我不确定它会在mozrepl中工作,但在Firefox附加组件中,您可以执行类似以下代码的操作。该代码将循环浏览所有打开的浏览器窗口。为每个窗口调用一个函数,在本例中为doWindow

Components.utils.import("resource://gre/modules/Services.jsm"); 
function forEachOpenWindow(fn) { 
    // Apply a function to all open browser windows 

    var windows = Services.wm.getEnumerator("navigator:browser"); 
    while (windows.hasMoreElements()) { 
     fn(windows.getNext().QueryInterface(Ci.nsIDOMWindow)); 
    } 
} 

function doWindow(curWindow) { 
    var tabContainer = curWindow.getBrowser().tabContainer; 
    var tabs = tabContainer.childNodes; 
    //Do what you are wanting to do with the tabs in this window 
    // then move to the next. 
} 

forEachOpenWindow(doWindow); 

您可以创建一个由仅仅有doWindow添加任何标签,它从tabContainer.childNodes获得一个整体的名单包含了所有当前选项卡的数组。我在这里没有这样做,因为你从tabContainer.childNodes获得的是live collection,你还没有说明你是如何使用这个数组的。您的其他代码可能会(也可能不会)假设列表是实时的。

如果你一定要所有的标签是在一个阵列中,你可以有doWindow如下所示:

var allTabs = []; 
function doWindow(curWindow) { 
    var tabContainer = curWindow.getBrowser().tabContainer; 
    var tabs = tabContainer.childNodes; 
    //Explicitly convert the live collection to an array, then add to allTabs 
    allTabs = allTabs.concat(Array.prototype.slice.call(tabs)); 
} 

注:通过最初是从Converting an old overlay-based Firefox extension into a restartless addon这是作者采取窗口的代码回路在MDN上重新编写为How to convert an overlay extension to restartless的初始部分。

+1

我不能给你upvote,但非常感谢! –

相关问题