Open a new tab with "hello world" on it

201 Views Asked by At

How to open new tab, and create a new HTML document in it? Preferably using old restart-required API, like Components.classes, Components.interfaces stuff, but any way that works is fine.

1

There are 1 best solutions below

0
On BEST ANSWER

In one of my add-ons, I use the following code to open a URL in either a tab or a window:

/**
 * Open a URL in a window or a tab.
 */
 function openUrlInWindowOrTab(url, titleText, inWindow, makeTabActive) {
    // Default: in tab; tab not activated
    if(typeof (url) !== "string" ) {
        return;
    }//else
    //  Add/remove a "/" to comment/un-comment the code appropriate for your add-on type.
    /* Add-on SDK:
    let activeWindow = require('sdk/window/utils').getMostRecentBrowserWindow();
    //*/
    //* Overlay and bootstrap (from almost any context/scope):
    Components.utils.import("resource://gre/modules/Services.jsm"); //Services
    let activeWindow = Services.wm.getMostRecentWindow("navigator:browser");        
    //*/
    let gBrowser = activeWindow.gBrowser;

    if(inWindow) {
        // Set default title
        titleText = (typeof titleText === "string") ? titleText : "Opened by [Your add-on]";
        //Open a window
        return activeWindow.open(url, titleText);
    } else {
        //Open a tab
        let newTab = gBrowser.addTab(url);
        if(makeTabActive) {
            //Make the tab active
            gBrowser.selectedTab = newTab;
        }
        return newTab;
    }
}

The above should work in Overlay and Bootstrapped add-ons. It can also work in the Add-on SDK by uncommenting the code for the Add-on SDK and commenting out the Overlay/bootstrapped code (the line(s) that get the activeWindow). However, for the Add-on SDK, it would be better to use the SDK specific APIs.

If you want it to say "Hello World" in the new tab, then provide an HTML file in your chrome/content directory and use an appropriate URL for it (e.g. chrome://[as defined in your chrome.manifest]/content/helloWorld.html), as defined for your add-on in a content line in your chrome.manifest.