2015-06-24 115 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,但非常感謝! –

相關問題