Alex
Alex

Reputation: 75

How to replace or destroy a tab using the Firefox Add-on SDK?

I did not find anything in the Firefox Add-on SDK (Tab API) that can destroy a tab or replace it with a new tab. I can find the Tab ID, Tab URL, or other identifier. Is there any way to replace or destroy a tab?

Upvotes: 0

Views: 84

Answers (2)

willlma
willlma

Reputation: 7533

Use tab.close(callback).

What do you mean by replace? If you just want to change the URL, then use tab.url = url.

Upvotes: 3

Noitidart
Noitidart

Reputation: 37238

I don't know about SDK, but you can destroy and replace one tab with another tab.

This is how to do it with non-sdk:

How to close a tab by its "id"

var tabIdToClose = 'panel-3-1';

Cu.import('resource://gre/modules/Services.jsm');
var DOMWindows = Services.wm.getEnumerator('navigator:browser');
while (DOMWindows.hasMoreElements()) {
    var aDOMWindow = DOMWindows.getNext();
    if (aDOMWindow.gBrowser && aDOMWindow.gBrowser.tabContainer) {
        var tabs = aDOMWindow.gBrowser.tabContainer.childNodes;
        for (var i = 0; i < tabs.length; i++) {
            var aTab = tabs[i];
            var aTabId = aTab.getAttribute('linkedpanel');
            console.log('tab id:', aTabId);
            if (aTabId == tabIdToClose) {
                aDOMWindow.gBrowser.removeTab(aTab);
            }
        }
    } else {
        //this window does not have any tabs
    }
}

This is how to replace tab with another tab and close the first tab.

var tabIdToReplace = 'panel-3-248';
var tabIdToReplaceWith = 'panel-3-246'; //this tab will be closed, but its contents will be in tabIdToReplace

var aTabToReplace;
var aTabToReplaceWith;

Cu.import('resource://gre/modules/Services.jsm');
var DOMWindows = Services.wm.getEnumerator('navigator:browser');
while (DOMWindows.hasMoreElements()) {
    var aDOMWindow = DOMWindows.getNext();
    if (aDOMWindow.gBrowser && aDOMWindow.gBrowser.tabContainer) {
        var tabs = aDOMWindow.gBrowser.tabContainer.childNodes;
        for (var i = 0; i < tabs.length; i++) {
            var aTab = tabs[i];
            var aTabId = aTab.getAttribute('linkedpanel');
            console.log('tab id:', aTabId);
            if (aTabId == tabIdToReplace) {
                aTabToReplace = aTab;
            } else if (aTabId == tabIdToReplaceWith) {
                aTabToReplaceWith = aTab;
            }
            if (aTabToReplace && aTabToReplaceWith) {
                aTabToReplaceWith.ownerDocument.defaultView.gBrowser.swapBrowsersAndCloseOther(aTabToReplace, aTabToReplaceWith);
                break;
            }
        }
    } else {
        //this window does not have any tabs
    }
}

If you just want to swap the tabs without closing either then do this

I havent completed this so the swap isn't perfect, like I have to set the iconURL and title of the tab that would have been closed: https://gist.github.com/Noitidart/9b335a460f53b0390336

Upvotes: 2

Related Questions