Making a Firefox Addon Do Something

As it turns out, hooking up Javascript to XUL so that an addon can actually do something is remarkably similar to linking HTML and Javascript together when doing web development.  The first step is to create a Javascript file and include it it in the XUL file much like you would include a Javascript file in an HTML file:

<overlay id="ehow_earnings_tracker_overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
    <script type="application/x-javascript" src="chrome://ehow_earnings_tracker/content/browser_overlay.js" />
    <statusbar id="status-bar">
        <statusbarpanel id="ehow_earnings_tracker_statusbar" label="" />
    </statusbar>
</overlay>

Now we can add code in browser_overlay.js to actually do something.  In this case, we will update the status bar text with the URL of HTML page that was loaded:

// Creates a global variable called "ehow_earnings_tracker"
var ehow_earnings_tracker =
{
    init:
        function()
        {
            // Grab the contents of the browser
            var appcontent = document.getElementById("appcontent");
            if(appcontent)
            {
                // Get notified when the page is done loading
                appcontent.addEventListener("DOMContentLoaded", ehow_earnings_tracker.onPageLoad, true);
            }
        },

    onPageLoad:
        function(aEvent)
        {
            var doc = aEvent.originalTarget; // doc is document that triggered "onload" event
            var statusBar = document.getElementById("ehow_earnings_tracker_statusbar");

            if(!statusBar)
            {
                return;
            }

            statusBar.setAttribute("label", doc.location.href);
        }
};

// Hook into the window load event
window.addEventListener("load", ehow_earnings_tracker.init, false)

Now, when I run Firefox with my plugin enabled it dynamically updates the status bar with the URL of the loaded page:

url in statusbar

One Comment

  1. GD says:

    Extremely well documented. GD

Leave a Reply