Open Tab in a Specific Position by Firefox extension

190 views Asked by At

Say, there are 10 tabs in Firefox browser window.

How can I add a tab in after 2nd tab by a Firefox extension code?

gBrowser.addTab method only appends to the tab list.

1

There are 1 answers

2
Makyen On BEST ANSWER

There is no easy, direct way of doing what you want. If you really want to open a tab directly at a specific index then you can take a look at the code for gBrowser.addTab() and the code for gBrowser.moveTabTo(); copy them and modify them to do what you want. Note that this code is in an XML representation of JavaScript. Thus, you will need to reformat it a bit if you want to use it.

However, the easy way to do this is to open the tab, gBrowser.addTab(). Then, move it to the index that you desire, gBrowser.moveTabTo().

The following code will do what you want. When I attached this code to a button, the tab visually appeared to open at the index specified. It did not open first at the end of the tabs and then appear to move. There was no user noticeable difference between doing this, adding then moving, instead of actually adding the tab at the specified index.

function handleButtonCommandEvent(event) {
    let window = event.view;

    //Create the window variable if it does not exist. It should
    //  already be defined from event.view.
    //  This should work from any Firefox context.
    if (typeof window === "undefined") {
        //If there is no window defined, get the most recent.
        var window=Components.classes["@mozilla.org/appshell/window-mediator;1"]
                             .getService(Components.interfaces.nsIWindowMediator)
                             .getMostRecentWindow("navigator:browser");
    }

    //Test addTabAtIndex()
    addTabAtIndexInWindow(window, 2, "http://www.ebay.com/")
}

/**
 * Open a tab in specified window at index.
 */
function addTabAtIndexInWindow(window, index, URL, referrerURI, charset, postData,
                       owner, allowThirdPartyFixup ) {

    //Get the  gBrowser for the specified window
    let winGBrowser = window.gBrowser;

    //Open a new tab:
    let newTab = winGBrowser.addTab(URL, referrerURI, charset, postData,
                                    owner, allowThirdPartyFixup );
    //Immediately move it to the index desired:
    winGBrowser.moveTabTo(newTab,index);

}