Firefox XUL toolbar problem with javascript getElementById

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");

}


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).


您的工具栏是覆盖层,所以上下文(文档和窗口)是browser.xul,不包含您的html文件。

链接地址: http://www.djcxy.com/p/88016.html

上一篇: Chrome,获取选定的文本问题

下一篇: 使用javascript getElementById的Firefox XUL工具栏问题