views:

472

answers:

2

Hi all,

I'm writing my first Firefox XUL toolbar, and am getting a strange behavior - in order to debug my code, I call the same js function from both the firefox toolbar and from a button on a very simple HTML file I created.
The javascript function displays an alert window, gets an element using 'document.getElementById', changes its color, and displays another alert window.
The javascript function works well when called using the HTML button, but when using the toolbar button the 'document.getElementById' returns null and the function terminates (only the first alert window shows).

Any guess what can be wrong? I provide the (very simple) code below for refenrece.

Many thanks in advance!



The javascript file - facebrew.js

function FaceBrew_rtlSelection() { alert('Before!'); sel_node = document.getElementById("header"); sel_node.style.color = 'blue'; alert('After!'); }

The HTML file (without the leading space)

< !DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> < html xmlns="http://www.w3.org/1999/xhtml">

< head> < title>Test< /title> < script type="text/javascript" src="http://localhost/Sandbox/FaceBrew/chrome/content/facebrew.js"> < /script> < /head>

< body> < input type="button" value="Click me" id="select" onclick="FaceBrew_rtlSelection()" /> < div id="header"> < h1 >Hello world!< /h1> < /div> < /body> < /html>

The XUL file - facebrew.xul

<script type="application/x-javascript"
        src="chrome://facebrew/content/facebrew.js" />

<toolbox id="navigator-toolbox">
    <toolbar id="FaceBrew-Toolbar" toolbarname="FaceBrew Toolbar" accesskey="F"
             class="chromeclass-toolbar" context="toolbar-context-menu" 
             hidden="false" persist="hidden">
        <toolbaritem flex="0">            
            <toolbarbutton id="FaceBrew-Web-Button" tooltiptext=""
                           label="Run" oncommand="FaceBrew_rtlSelection()" />
        </toolbaritem>
    </toolbar>
</toolbox>

The CSS file - facbrew.css

FaceBrew-Web-Button {

list-style-image: url("chrome://facebrew/skin/web.png");

}

+1  A: 

Your toolbar is an overlay, so the context (document and window) is browser.xul, no your html file.

Paul Rouget
+1  A: 

as Paul said, when function is called from toolbar, document context is different. get your currently selected HTML document object with:

var doc = gBrowser.selectedBrowser.contentDocument;
doc.getElementById(...);

also, you can always take a look at error console to see why your code is failing (Tools -> Error Console).

parserr
Many thanks Paul and Nickolay! This solved the problem.
Omri Allouche